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

Some api responses, such as 500 – Internal server error is the same for all API endpoints.
Let’s see how to implement this 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

  c.OperationFilter<InternalServerErrorResponseFilter>(); 

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

Important!

Model above is default for asp.net 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:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s