简体   繁体   English

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

[英]Asp.net Web Api set response status code to number

In Asp.net Web Api, how do I set the status code of my response using an int or string, not the StatusCode enum?在 Asp.net Web Api 中,如何使用 int 或 string 而不是 StatusCode 枚举设置响应的状态代码?

In my case, I'd like to return validation errors with status code 422, "Unprocessable Entity", but there's no enumerator for it.就我而言,我想返回状态代码为 422,“不可处理的实体”的验证错误,但没有枚举器。

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

You can cast any int to a HttpStatusCode.您可以将任何 int 转换为 HttpStatusCode。

response.StatusCode = (HttpStatusCode)422;

You can also:你也可以:

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

I ended up creating a class for this:我最终为此创建了一个类:

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

which can be used like this:可以这样使用:

response.StatusCode = HttpStatusCodeAdditions.UnprocessableEntity;

将您的HttpStatusCode转换为整数:

response.StatusCode = Convert.ToInt32(HttpStatusCode.UnprocessableEntity)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 状态码 406 使用 ASP.NET 内核中的格式响应数据 Web API - Status code 406 using Format response data in ASP.NET Core Web API 返回自定义状态代码在ASP.Net Web API中不起作用 - Returning custom status code is not working in ASP.Net Web API Asp.net 5 web api返回状态码和正文 - Asp.net 5 web api return status code and body AngularJS使用Asp.net Web API:$ http post返回XMLHttpRequest无法加载:预检的响应具有无效的HTTP状态代码405 - AngularJS With Asp.net Web API: $http post returning XMLHttpRequest cannot load: Response for preflight has invalid HTTP status code 405 asp.net Web api AJAX状态0 - asp.net web api AJAX status 0 ASP.NET Core Web API 响应 - 状态代码与自定义对象 - ASP.NET Core Web API response - status codes vs custom object .net核心asp.net Web API操作返回意外状态代码 - .net core asp.net web api action returning unexpected status code ASP.Net Core 中间件无法设置异常状态码,因为“响应已经开始” - ASP.Net Core middleware cannot set status code on exception because "response has already started" 不可接受的响应 (406) 消息 Asp.NET 代码 Web API (C#) - Z303CB0EF9EDB9082D61BB0572AZ - Not Acceptable Response(406) Message Asp.NET Code Web API (C#) - .NET 5.0 对ASP.NET WEB API的Ajax调用返回200状态代码错误 - Ajax call to ASP.NET WEB API returning error for 200 status code
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM