Asp.net Web Api将响应状态码设置为数字

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

在我的情况下,我想返回validation错误状态码422,“不可处理的实体”,但没有它的枚举。

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

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

 response.StatusCode = (HttpStatusCode)422; 

你也可以:

 HttpResponseMessage response = Request.CreateResponse((HttpStatusCode)422, "Unprocessable Entity"); 

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

  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;