返回自定义HTTP状态code从的WebAPI 2端点自定义、状态、WebAPI、HTTP

2023-09-03 02:27:55 作者:百里红妆

我工作的一个服务的WebAPI 2,和端点目前返回 IHttpActionResult 。我想返回一个状态code 422 ,但因为它是不是在的HTTPStatus code 枚举,我很茫然,如何将它发送的,因为所有的构造函数需要的HTTPStatus code

目前的情况是,我回来 BadResult(消息),但返回 422 +消息将更具描述性和有用的为我的客户。任何想法?

解决方案

根据C#规格:

  

该组枚举类型可以取的值不被它的枚举成员限制。特别是,枚举的基础类型的任何值可以转换为枚举类型,成为该枚举类型的一个独特的有效值

因此​​,你可以施放状态code 422的HTTPStatus code。

例如控制器:

 使用System.Net;
使用System.Net.Http;
使用System.Web.Http;

命名空间CompanyName.Controllers.Api
{
    [途径preFIX(服务/空指令)]
    [使用AllowAnonymous]
    公共类NoOpController:ApiController
    {
        [路线]
        [HTTPGET]
        公共IHttpActionResult GetNoop()
        {
            返回新System.Web.Http.Results.ResponseMessageResult(
                Request.CreateErrorResponse(
                    (的HTTPStatus code)422,
                    新HTTPError这样的(出了问题)
                )
            );
        }
    }
}
 

I'm working on a service in WebAPI 2, and the endpoint currently returns an IHttpActionResult. I'd like to return a status code 422, but since it's not in the HttpStatusCode enumeration, I'm at a loss as to how it would be sent, since all of the constructors require a parameter of HttpStatusCode

ASP.NET Core 设置WebAPI 响应数据格式

As it stands now, I'm returning BadResult(message), but returning a 422 + message would be more descriptive and useful for my clients. Any ideas?

解决方案

According to C# specification:

The set of values that an enum type can take on is not limited by its enum members. In particular, any value of the underlying type of an enum can be cast to the enum type and is a distinct valid value of that enum type

Therefore you can cast status code 422 to HttpStatusCode.

Example controller:

using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace CompanyName.Controllers.Api
{
    [RoutePrefix("services/noop")]
    [AllowAnonymous]
    public class NoOpController : ApiController
    {
        [Route]
        [HttpGet]
        public IHttpActionResult GetNoop()
        {
            return new System.Web.Http.Results.ResponseMessageResult(
                Request.CreateErrorResponse(
                    (HttpStatusCode)422,
                    new HttpError("Something goes wrong")
                )
            );
        }
    }
}

 
精彩推荐
图片推荐