返回自定义HTTP状态code从的WebAPI 2端点 [英] Return Custom HTTP Status Code from WebAPI 2 endpoint

查看:1923
本文介绍了返回自定义HTTP状态code从的WebAPI 2端点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的一个服务的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

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

这篇关于返回自定义HTTP状态code从的WebAPI 2端点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆