Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.net Web Api set response status code to number

In Asp.net Web Api, how do I set the status code of my response using an int or string, not the StatusCode enum?

In my case, I'd like to return validation errors with status code 422, "Unprocessable Entity", but there's no enumerator for it.

HttpResponseMessage response = Request.CreateResponse(); response.StatusCode = HttpStatusCode.UnprocessableEntity; //error, not in enum 
like image 266
Josh Noe Avatar asked Feb 19 '13 19:02

Josh Noe


People also ask

How do you set a status code in response?

Methods to Set HTTP Status Code Sr.No. This method sets an arbitrary status code. The setStatus method takes an int (the status code) as an argument. If your response includes a special status code and a document, be sure to call setStatus before actually returning any of the content with the PrintWriter.


1 Answers

You can cast any int to a HttpStatusCode.

response.StatusCode = (HttpStatusCode)422; 

You can also:

HttpResponseMessage response = Request.CreateResponse((HttpStatusCode)422, "Unprocessable Entity"); 
like image 68
lolol Avatar answered Sep 20 '22 05:09

lolol