Josh Noe Josh Noe - 1 year ago 179
C# Question Web Api set response status code to number

In 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 Source

You can cast any int to a HttpStatusCode.

response.StatusCode = (HttpStatusCode)422;

You can also:

HttpResponseMessage response = Request.CreateResponse((HttpStatusCode)422, "Unprocessable Entity");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download