Return http 204 “no content” to client in ASP.NET MVC2

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

Leave a Comment