Josh Noe Josh Noe - 1 month ago 19
C# Question

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

Answer

You can cast any int to a HttpStatusCode.

response.StatusCode = (HttpStatusCode)422;

You can also:

HttpResponseMessage response = Request.CreateResponse((HttpStatusCode)422, "Unprocessable Entity");
Comments