ASP.NET WEB API documentation using Swagger – Global operation for 500 response code

Some api response codes, such as 500 for Internal server error, are the same for all API endpoints.
Let’s see how to implement such general behaviour using Swashbuckle.

Add below classes:

public class InternalServerErrorModel
    public string Message { get; set; }

    public string ExceptionMessage { get; set; }

    public string ExceptionType { get; set; }

    public string StackTrace { get; set; }

public class InternalServerErrorResponseFilter : IOperationFilter
    public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        var schema = schemaRegistry.GetOrRegister(typeof(InternalServerErrorModel));

        if (!operation.responses.ContainsKey("500"))
            operation.responses.Add(new KeyValuePair<string, Response>("500", new Response()
                description = "Internal server error occured",
                schema = schema

Register new operation filter in SwaggerConfig.cs


And after running the application, each endpoint descriptions is decorated with:


Model above is default for web api, but it is security issue to expose internal details such Exception stack trace to outside world. Much better is to log exceptions to database using, for example, ELMAH library, and return just Error ID to clients.

This entry was posted in Documentation, WEB API and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.