Asp.net Web Api set response status code to number

前端 未结 3 1619
悲哀的现实
悲哀的现实 2021-02-06 21:53

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

相关标签:
3条回答
  • 2021-02-06 22:22

    Convert your HttpStatusCode to integer:

    response.StatusCode = Convert.ToInt32(HttpStatusCode.UnprocessableEntity)
    
    0 讨论(0)
  • 2021-02-06 22:31

    You can cast any int to a HttpStatusCode.

    response.StatusCode = (HttpStatusCode)422;
    

    You can also:

    HttpResponseMessage response = Request.CreateResponse((HttpStatusCode)422, "Unprocessable Entity");
    
    0 讨论(0)
  • 2021-02-06 22:43

    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;
    
    0 讨论(0)
提交回复
热议问题