Pau*_*own 207 asp.net-mvc
我正在编写一个接受来自第三方服务的POST数据的应用程序.
当此数据被POST时,我必须返回200 HTTP状态代码.
我怎么能从我的控制器那里做到这一点?
Bri*_*ehm 375
在你的控制器中,你将返回一个像这样的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
}
Run Code Online (Sandbox Code Playgroud)
Kev*_*ker 50
200只是成功请求的正常HTTP标头.如果这一切你所需要的,只是有控制器return new EmptyResult();
Jac*_*ack 39
您可以简单地将响应的状态代码设置为200,如下所示
public ActionResult SomeMethod(parameters...)
{
//others code here
...
Response.StatusCode = 200;
return YourObject;
}
Run Code Online (Sandbox Code Playgroud)
Bri*_*den 19
[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 });
}
}
Run Code Online (Sandbox Code Playgroud)
在 .NET Core 中执行此操作的方法(在撰写本文时)如下:
public async Task<IActionResult> YourAction(YourModel model)
{
if (ModelState.IsValid)
{
return StatusCode(200);
}
return StatusCode(400);
}
Run Code Online (Sandbox Code Playgroud)
所述的StatusCode方法返回的类型StatusCodeResult它实现IActionResult并且因此可以用作您的动作的返回类型。
作为重构,您可以通过使用 HTTP 状态代码枚举的强制转换来提高可读性,例如:
return StatusCode((int)HttpStatusCode.OK);
Run Code Online (Sandbox Code Playgroud)
此外,您还可以使用一些内置的结果类型。例如:
return Ok(); // returns a 200
return BadRequest(ModelState); // returns a 400 with the ModelState as JSON
Run Code Online (Sandbox Code Playgroud)
参考 StatusCodeResult - https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.statuscoderesult?view=aspnetcore-2.1
归档时间: |
|
查看次数: |
134569 次 |
最近记录: |