Jer*_*ond 26 httpresponse asp.net-mvc-2
在我所拥有的ASP.net MVC 2应用程序中,我想要对post操作返回204 No Content响应.当前我的控制器方法有一个void返回类型,但这会将客户端的响应发送回200 OK,并将Content-Length标头设置为0.如何将响应发送到204?
[HttpPost]
public void DoSomething(string param)
{
// do some operation with param
// now I wish to return a 204 no content response to the user
// instead of the 200 OK response
}
Run Code Online (Sandbox Code Playgroud)
Sco*_*ott 36
在MVC3中有一个HttpStatusCodeResult类.您可以为MVC2应用程序滚动自己:
public class HttpStatusCodeResult : ActionResult
{
private readonly int code;
public HttpStatusCodeResult(int code)
{
this.code = code;
}
public override void ExecuteResult(System.Web.Mvc.ControllerContext context)
{
context.HttpContext.Response.StatusCode = code;
}
}
Run Code Online (Sandbox Code Playgroud)
您必须改变您的控制器方法,如下所示:
[HttpPost]
public ActionResult DoSomething(string param)
{
// do some operation with param
// now I wish to return a 204 no content response to the user
// instead of the 200 OK response
return new HttpStatusCodeResult(HttpStatusCode.NoContent);
}
Run Code Online (Sandbox Code Playgroud)
Per*_*rcy 15
您可以简单地返回 IHttpActionResult 并使用StatusCode:
public IHttpActionResult DoSomething()
{
//do something
return StatusCode(System.Net.HttpStatusCode.NoContent);
}
Run Code Online (Sandbox Code Playgroud)
Sam*_*amo 11
您可以返回一个NoContentActionResult。
[HttpPost("Update")]
public async Task<IActionResult> DoSomething(object parameters)
{
// do stuff
return NoContent();
}
Run Code Online (Sandbox Code Playgroud)