在Asp.net Web Api中,如何使用int或字符串设置响应的状态代码,而不是StatusCode枚举?
在我的情况下,我希望返回状态代码为422" Unprocessable Entity"的验证错误,但是没有枚举器。
HttpResponseMessage response = Request.CreateResponse();
response.StatusCode = HttpStatusCode.UnprocessableEntity; //error, not in enum
答案 0 :(得分:44)
您可以将任何int转换为HttpStatusCode。
response.StatusCode = (HttpStatusCode)422;
你也可以:
HttpResponseMessage response = Request.CreateResponse((HttpStatusCode)422, "Unprocessable Entity");
答案 1 :(得分:10)
我最终为此创建了一个类:
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;
答案 2 :(得分:0)
将您的 HttpStatusCode 转换为整数:
response.StatusCode = Convert.ToInt32(HttpStatusCode.UnprocessableEntity)