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;
- WebAPI多个Put / Post参数
- ASP.NET Core API只返回列表的第一个结果
- 在apicontroller中无法从OwinContext获取UserManager
- 任何人都可以解释给我的CreatedAtRoute()?
- 带有AuthorizeAttribute的ASP.NET Web API授权
- WebAPI中的DependencyResolver.SetResolver和HttpConfiguration.DependencyResolver之间有什么区别
- 如何将整数数组传递给ASP.NET Web API?
- 浏览器取消请求时出现ASP.NET Web API OperationCanceledException
- 对Asp.Net WebApi的angular度,在服务器上实现CSRF