Return Custom HTTP Status Code from WebAPI 2 endpoint

后端 未结 6 1002
陌清茗
陌清茗 2021-02-01 12:34

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

6条回答
  •  轮回少年
    2021-02-01 13:26

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

提交回复
热议问题