Return Custom HTTP Status Code from WebAPI 2 endpoint

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

    I'm using a custom Filter in my controllers that catches any exceptions and returns custom error results so I needed a way to return a custom message response based on the exception message.

    I'm using JsonResult (found in the Microsoft.AspNetCore.Mvc namespace) to return a custom status code and messagesas such:

    public class DomainViolationFilter : ExceptionFilterAttribute
        {
            public override void OnException(ExceptionContext context)
            {
                switch (context.Exception)
                {
                    case EntityNotFoundException e:
                        JsonResult toReturn = new JsonResult(e);
                        toReturn.StatusCode = 404;
                        context.Result = toReturn;
                        return;
                }
            }
        }
    

    In my case, I'm serializing directly the exception object (ex) for simplicity but you should be returning only the relevant (and safe) data, or whatever you need in your use case.

提交回复
热议问题