如何从ASP.NET MVC 3控制器返回一个200 HTTP状态代码

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

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

我怎么能从我的控制器做到这一点?

在你的控制器中,你会返回一个像这样的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只是成功请求的普通HTTP头。 如果这就是你所需要的,只需让控制器return new EmptyResult();

您可以简单地将响应的状态码设置为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 }); } }