在我拥有的ASP.net MVC 2应用程序中,我想对后操作返回204 No Content响应。当前,我的 Controller 方法的返回类型为void,但这会以200 OK的方式将响应发送回客户端,并且Content-Length header 设置为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;
    }
}

您必须像这样更改 Controller 方法:
[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);
}

关于c# - 将http 204 “no content”返回到ASP.NET MVC2中的客户端,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4513583/

10-12 01:22
查看更多