Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 644
swannee Avatar asked Mar 10 '15 01:03

swannee


1 Answers

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.

like image 159
Kiran Avatar answered Oct 17 '22 01:10

Kiran