Return http 204 "no content" to client in ASP.NET MVC2
Asked Answered
M

5

45

In an ASP.net MVC 2 app that I have I want to return a 204 No Content response to a post operation. 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?

[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
}
Men answered 22/12, 2010 at 20:50 Comment(0)
S
47

In MVC3 there is an HttpStatusCodeResult class. You could roll your own for an MVC2 application:

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);
}
Shippee answered 22/12, 2010 at 20:56 Comment(0)
T
25

You can simply return a IHttpActionResult and use StatusCode:

public IHttpActionResult DoSomething()
{
    //do something

    return StatusCode(System.Net.HttpStatusCode.NoContent);        
}
Tycoon answered 24/4, 2019 at 7:56 Comment(0)
N
24

Update as of ASP.NET Core 1.0+ (2016)

You can return a NoContent ActionResult.

[HttpPost("Update")]
public async Task<IActionResult> DoSomething(object parameters)
{
    // do stuff
    return NoContent();
}
Nope answered 12/3, 2019 at 23:55 Comment(0)
S
0

FYI, i am using your approach and it is returning 204 No Content (just return a void), i think you have another problem

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

    //returning nothing
}
Shouldst answered 8/4, 2018 at 15:50 Comment(4)
Are you sure you are using MVC, not WebAPI?Anklet
WebAPI @AnkletShouldst
in Web API void methods return 204, but in MVC they return 200.Anklet
How do you comunicate an error? Like if ( somethingWentWrong) return 400 else return 204Actinolite
V
0

For .net 6 plus the new approach is

        public IActionResult MyAction()
        {
            return NoContent();
        }
Vedda answered 4/8, 2023 at 9:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.