在ASP.NET MVC2中将http 204“无内容”返回给客户端

问题描述 投票:25回答:4

在我所拥有的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
}
asp.net-mvc-2 httpresponse
4个回答
34
投票

在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);
}

2
投票

在ASP.NET Core 2中,您可以使用NoContent

[HttpPost("Update")]
public async Task<IActionResult> DoSomething(object parameters)
{
    return NoContent();
}

0
投票

仅供参考,我正在使用您的方法,它正在返回204 No Content(只是返回空白),我认为您还有另一个问题

[HttpPost]
public void SetInterests(int userid, [FromBody] JObject bodyParams)
{
     ....
     .....

    //returning nothing
}

0
投票

您只需返回IHttpActionResult并使用StatusCode

public IHttpActionResult DoSomething()
{
    //do something

    return StatusCode(System.Net.HttpStatusCode.NoContent);        
}
© www.soinside.com 2019 - 2024. All rights reserved.