Swashbuckle general response codes

Niek Jannink from

Is there some way to define 'general' response codes that are applicable for all calls.

Eg all calls can return one of the following:

400 - Bad request
500 - Internal server error (unknown exception occurred)
503 - Service unavailable (maintenance mode)

Instead of copy-pasting the comments and attributes on every end-point it would be nice if I can define it in some central place.

asp.net-core-mvc swagger swashbuckle

Answers

answered 6 days ago Niek Jannink #1

Thanks @HelderSepu indeed IDocumentFilter is the solution

// Swagger config
swagger.DocumentFilter<DefaultFilter>();

internal class DefaultFilter : IDocumentFilter
{
    public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
    {
        foreach (var item in swaggerDoc.Paths.Values)
        {
            UpdateItem(item, "400", "Bad or malformed request.");
            UpdateItem(item, "500", "Internal server error.");
            UpdateItem(item, "503", "Service in maintenance mode.");
        }
    }

    private static void UpdateItem(PathItem item, string key, string description)
    {
        TrySetValue(item.Get, key, description);
        TrySetValue(item.Put, key, description);
    }

    private static void TrySetValue(Operation op, string key, string description)
    {
        if ( (op == null) || (op.Responses.ContainsKey(key)) )
        {
            return;
        }

        op.Responses.Add(key, new Response
        {
            Description = description,
        });
    }
}