Return Custom HTTP Status Code from WebAPI 2 endpoint

后端 未结 6 938
陌清茗
陌清茗 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:10

    For this you may need to use an Action Filter Attribute. Nothing fancy. Just create a class and inherit it from ActionFilterAttribute class in c#. Then override a method named OnActionExecuting to implement this. Then just use this filter on the head of any controller. Following is a demo.

    On the condition when you need to produce custom status code based message in ActionFilterAttribute you can write in following way:

            if (necessity_to_send_custom_code)
            {
                actionContext.Response = actionContext.Request.CreateResponse((HttpStatusCode)855, "This is custom error message for you");
            }
    

    Hope this helps.

提交回复
热议问题