Skip to content

JsonExceptionFilterAttribute

Rico Suter edited this page Nov 2, 2018 · 6 revisions
  • Package: NSwag.AspNetCore or NSwag.AspNet.WebApi

Usually, the JSON serializer of ASP.NET Core or 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 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.

ASP.NET Core

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

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());
    ...