39

在 Asp.net Web Api 中,如何使用 int 或字符串而不是 StatusCode 枚举来设置响应的状态代码?

就我而言,我想返回带有状态代码 422“无法处理的实体”的验证错误,但它没有枚举器。

HttpResponseMessage response = Request.CreateResponse();
response.StatusCode = HttpStatusCode.UnprocessableEntity; //error, not in enum
4

3 回答 3

47

您可以将任何 int 转换为 HttpStatusCode。

response.StatusCode = (HttpStatusCode)422;

你也可以:

HttpResponseMessage response = Request.CreateResponse((HttpStatusCode)422, "Unprocessable Entity");
于 2013-02-19T19:47:21.130 回答
11

我最终为此创建了一个类:

  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;
        }
    }

可以这样使用:

response.StatusCode = HttpStatusCodeAdditions.UnprocessableEntity;
于 2015-02-04T19:45:04.430 回答
0

将您的HttpStatusCode转换为整数:

response.StatusCode = Convert.ToInt32(HttpStatusCode.UnprocessableEntity)
于 2019-12-04T16:50:35.803 回答