在 Asp.net Web Api 中,如何使用 int 或字符串而不是 StatusCode 枚举来设置响应的状态代码?
就我而言,我想返回带有状态代码 422“无法处理的实体”的验证错误,但它没有枚举器。
HttpResponseMessage response = Request.CreateResponse();
response.StatusCode = HttpStatusCode.UnprocessableEntity; //error, not in enum
在 Asp.net Web Api 中,如何使用 int 或字符串而不是 StatusCode 枚举来设置响应的状态代码?
就我而言,我想返回带有状态代码 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");
我最终为此创建了一个类:
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;
将您的HttpStatusCode转换为整数:
response.StatusCode = Convert.ToInt32(HttpStatusCode.UnprocessableEntity)