swannee swannee - 3 months ago 25
JSON Question

Returning JSON Errors from Asp.Net MVC 6 API

I'm trying out building a web API with MVC 6. But when one of my controller methods throws an error, the content of the response is a really nicely formatted HTML page that would be very informative were this an MVC app. But since this is an API, I'd rather have some JSON returned instead.

Note: My setup is super basic right now, just setting:

app.UseStaticFiles();
app.UseIdentity();

// Add MVC to the request pipeline.
app.UseMvc();


I want to set this up universally. Is there a "right/best" way to set this up in MVC 6 for an API?

Thanks...

Answer

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.