[英]Return http 204 “no content” to client in ASP.NET MVC2
In an ASP.net MVC 2 app that I have I want to return a 204 No Content response to a post operation.在我拥有的 ASP.net MVC 2 应用程序中,我想向发布操作返回 204 No Content 响应。 Current my controller method has a void return type, but this sends back a response to the client as 200 OK with a Content-Length header set to 0. How can I make the response into a 204?当前我的控制器方法有一个 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
}
In MVC3 there is an HttpStatusCodeResult class .在 MVC3 中有一个HttpStatusCodeResult 类。 You could roll your own for an MVC2 application:您可以为 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;
}
}
You'd have to alter your controller method like so:你必须像这样改变你的控制器方法:
[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);
}
You can simply return a IHttpActionResult and use StatusCode
:您可以简单地返回 IHttpActionResult 并使用StatusCode
:
public IHttpActionResult DoSomething()
{
//do something
return StatusCode(System.Net.HttpStatusCode.NoContent);
}
FYI, i am using your approach and it is returning 204 No Content (just return a void), i think you have another problem仅供参考,我正在使用你的方法,它返回 204 No Content(只返回一个空值),我认为你有另一个问题
[HttpPost]
public void SetInterests(int userid, [FromBody] JObject bodyParams)
{
....
.....
//returning nothing
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.