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
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.