在ASP.net MVC 2应用程序中,我想要返回一个204无内容响应的后期操作。当前我的控制器方法有一个无效的返回类型,但是它将一个响应发送回到客户端为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 }
解决方法
在MVC3中有一个
HttpStatusCodeResult class.你可以自己滚动一个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; } }
你必须像这样改变你的控制器方法:
[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); }