如何从ASP返回200 HTTP状态码。NET MVC 3控制器

我正在编写一个接受来自第三方服务的POST数据的应用程序。

当这个数据被post时,我必须返回一个200 HTTP状态码。

我如何从我的控制器做到这一点?

196285 次浏览

200只是一个成功请求的正常HTTP报头。如果你需要的是所有,只要有控制器return new EmptyResult();

在你的控制器中,你会像这样返回一个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
}

您可以简单地将响应的状态代码设置为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方法返回类型为StatusCodeResult,该类型实现了IActionResult,因此可以用作您的操作的返回类型。

作为一种重构,你可以通过使用HTTP状态码枚举的类型转换来提高可读性,比如:

return StatusCode((int)HttpStatusCode.OK);

此外,还可以使用一些内置的结果类型。例如:

return Ok(); // returns a 200
return BadRequest(ModelState); // returns a 400 with the ModelState as JSON

引用StatusCodeResult - https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.statuscoderesult?view=aspnetcore-2.1