JsonExceptionFilterAttribute

Rico Suter edited this page Dec 15, 2017 · 5 revisions
  • Package: NSwag.AspNet.WebApi or NSwag.AspNetCore

Usually, Web API does not fully serialize thrown exceptions (the inheritance hierarchy, stack trace and inner exceptions are missing). This is why this project provides a Web API filter which takes over the serialization process of exceptions.

Add filter to a single controller

[JsonExceptionFilter]
public class PersonController : ApiController
{

Register globally

Just register the filter in your Web API project. The following sample shows how to register the filter for all Web API actions.

OWIN and Global.asax

Add the custom filter to the HttpConfiguration object in your Startup.cs (ASP.NET)...

public void Configuration(IAppBuilder app)
{
    var config = new HttpConfiguration();
    config.Filters.Add(new JsonExceptionFilterAttribute());

... or to the MVC options (ASP.NET Core)

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc(options => options.Filters.Add(new JsonExceptionFilterAttribute()));
    ...

... or Application_Start() method (Global.asax):

protected void Application_Start()
{
    GlobalConfiguration.Configuration.Filters.Add(new JsonExceptionFilterAttribute());
    ...

ASP.NET Core

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc(options =>
        {
            options.Filters.Add(new JsonExceptionFilterAttribute());
        });
    }