【发布时间】:2011-07-01 15:55:08
【问题描述】:
我正在编写一个从第三方服务接受 POST 数据的应用程序。
发布此数据后,我必须返回 200 HTTP 状态代码。
如何从我的控制器执行此操作?
【问题讨论】:
标签: asp.net-mvc
我正在编写一个从第三方服务接受 POST 数据的应用程序。
发布此数据后,我必须返回 200 HTTP 状态代码。
如何从我的控制器执行此操作?
【问题讨论】:
标签: asp.net-mvc
在您的控制器中,您将返回一个像这样的 HttpStatusCodeResult...
[HttpPost]
public ActionResult SomeMethod(...your method parameters go here...)
{
// todo: put your processing code here
//If not using MVC5
return new HttpStatusCodeResult(200);
//If using MVC5
return new HttpStatusCodeResult(HttpStatusCode.OK); // OK = 200
}
【讨论】:
int 和HttpStatusCode 的重载。
200 只是成功请求的正常 HTTP 标头。如果这就是您所需要的全部,只需使用控制器return new EmptyResult();
【讨论】:
HttpStatusCodeResult(...),因为它更明确地说明了您要实现的目标。根据接受的答案。
您可以简单地将响应的状态码设置为 200,如下所示
public ActionResult SomeMethod(parameters...)
{
//others code here
...
Response.StatusCode = 200;
return YourObject;
}
【讨论】:
[HttpPost]
public JsonResult ContactAdd(ContactViewModel contactViewModel)
{
if (ModelState.IsValid)
{
var job = new Job { Contact = new Contact() };
Mapper.Map(contactViewModel, job);
Mapper.Map(contactViewModel, job.Contact);
_db.Jobs.Add(job);
_db.SaveChanges();
//you do not even need this line of code,200 is the default for ASP.NET MVC as long as no exceptions were thrown
//Response.StatusCode = (int)HttpStatusCode.OK;
return Json(new { jobId = job.JobId });
}
else
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json(new { jobId = -1 });
}
}
【讨论】:
在 .NET Core 中执行此操作的方法(在撰写本文时)如下:
public async Task<IActionResult> YourAction(YourModel model)
{
if (ModelState.IsValid)
{
return StatusCode(200);
}
return StatusCode(400);
}
StatusCode 方法返回一种实现 IActionResult 的 StatusCodeResult 类型,因此可以用作您的操作的返回类型。 p>
作为重构,您可以通过使用 HTTP 状态代码枚举类型来提高可读性,例如:
return StatusCode((int)HttpStatusCode.OK);
此外,您还可以使用一些内置的结果类型。例如:
return Ok(); // returns a 200
return BadRequest(ModelState); // returns a 400 with the ModelState as JSON
参考。 StatusCodeResult - https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.statuscoderesult?view=aspnetcore-2.1
【讨论】: