Skip to content

JsonExceptionFilterAttribute

Rico Suter edited this page Nov 28, 2016 · 6 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...

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

... or Application_Start() method:

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