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
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.
You can cast any int to a HttpStatusCode.
response.StatusCode = (HttpStatusCode)422;
You can also:
HttpResponseMessage response = Request.CreateResponse((HttpStatusCode)422, "Unprocessable Entity");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With