Answers:
在您的控制器中,您将像这样返回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
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: //docs.microsoft.com/zh-cn/dotnet/api/microsoft.aspnetcore.mvc.statuscoderesult ? view = aspnetcore- 2.1