40

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

3 Answers 3

47

You can cast any int to a HttpStatusCode.

response.StatusCode = (HttpStatusCode)422;

You can also:

HttpResponseMessage response = Request.CreateResponse((HttpStatusCode)422, "Unprocessable Entity");
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! Exactly what I need! In your 2nd example, the 2nd parameter is for the content of the response. Passing "Unprocessable Entity" may be a little redundant. For example, I'm doing this: Request.CreateResponse((HttpStatusCode)422, validationErrors);
Yeh, that is it! The second parameter can be anything. =)
The extension method CreateResponse can be found in namespace "System.Net.Http".
11

I ended up creating a class for this:

  public class HttpStatusCodeAdditions
    {
        public const int UnprocessableEntityCode = 422;
        public static HttpStatusCodeAdditions UnprocessableEntity = new HttpStatusCodeAdditions(UnprocessableEntityCode);

        private HttpStatusCodeAdditions(int code)
        {
            Code = code;
        }
        public int Code { get; private set; }

        public static implicit operator HttpStatusCode(HttpStatusCodeAdditions addition)
        {
            return (HttpStatusCode)addition.Code;
        }
    }

which can be used like this:

response.StatusCode = HttpStatusCodeAdditions.UnprocessableEntity;

1 Comment

Nice and clean, i like it !
0

Convert your HttpStatusCode to integer:

response.StatusCode = Convert.ToInt32(HttpStatusCode.UnprocessableEntity)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.