Returning JSON Errors from Asp.Net MVC 6 API Returning JSON Errors from Asp.Net MVC 6 API json json

Returning JSON Errors from Asp.Net MVC 6 API


One way to achieve your scenario is to write an ExceptionFilter and in that capture the necessary details and set the Result to be a JsonResult.

// Here I am creating an attribute so that you can use it on specific controllers/actions if you want to.public class CustomExceptionFilterAttribute : ExceptionFilterAttribute{    public override void OnException(ExceptionContext context)    {        var exception = context.Exception;        context.Result = new JsonResult(/*Your POCO type having necessary details*/)        {            StatusCode = (int)HttpStatusCode.InternalServerError        };    }}

You can add this exception filter to be applicable to all controllers.Example:

app.UseServices(services =>{    services.AddMvc();    services.Configure<MvcOptions>(options =>    {        options.Filters.Add(new CustomExceptionFilterAttribute());    });.....}

Note that this solution does not cover all scenarios...for example, when an exception is thrown while writing the response by a formatter.