Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 } 
like image 751
Jeremy Raymond Avatar asked Dec 22 '10 20:12

Jeremy Raymond


People also ask

How can I return 204 without content?

you may indicate that a GET endpoint that returns a collection of resources will return 204 if the collection is empty. In this case GET /complaints/year/2019/month/04 may return 204 if there are no complaints filed in April 2019. This is not an error on the client side, so we return a success status code (204).


1 Answers

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); } 
like image 85
Scott Avatar answered Sep 27 '22 21:09

Scott