Swashbuckle.AspNetCore.Filters Documentation

repository·master·Indexed 19 days ago

https://github.com/mattfrear/swashbuckle.aspnetcore.filters

A collection of filters for Swashbuckle.AspNetCore to enhance Swagger documentation. It provides capabilities for adding custom request and response examples via IExamplesProvider or XML comments, injecting request and response headers, and automatically adding authorization indicators and security requirements for OAuth2/JWT to endpoint summaries.

Tokens
4.9K
Snippets
14
Records
20
Agent score
16%

What's inside Swashbuckle.AspNetCore.Filters

  1. Append Authorization status to endpoint summaries

    master

    The AppendAuthorizeToSummaryOperationFilter adds an indicator (e.g., (Auth)) to the action's summary in Swagger UI if the endpoint has an [Authorize] attribute. This helps developers quickly identify which endpoints require authentication.

    Note: You must call c.IncludeXmlComments(...) before adding this filter.

  2. JSON Serialization for Swagger Examples

    master

    Swagger examples are rendered using the same JSON serializer configuration used by your controllers in services.AddControllers().

    For Minimal APIs (.NET 5+), the library defaults to System.Text.Json.JsonSerializerDefaults.Web, which results in camelCase output. Note that PascalCase is not supported for Minimal APIs.

  3. Prefer XML comments over ExamplesOperationFilter

    master

    Since May 2018, Swashbuckle.AspNetCore supports adding examples directly via XML comments. This is the recommended approach and should be used instead of ExamplesOperationFilter whenever possible. XML comments work for request/response bodies and even for querystring or route parameters (e.g., on GET requests).

    Use the <example> tag within a <summary> or on a property to define the example value.

    public class Product
    {
        /// <summary>
        /// The name of the product
        /// </summary>
        /// <example>Men's basketball shoes</example>
        public string Name { get; set; }
    }
  4. Add security requirements for OAuth2/JWT

    master

    The SecurityRequirementsOperationFilter adds security information to each operation, enabling the 'Authorize' button in Swagger UI. This allows users to send an Authorization header (e.g., a Bearer token) to protected endpoints.

    To use this, you must also define the security scheme using c.AddSecurityDefinition.

  5. Add Request and Response examples to Swagger

    master

    The Request and Response example filters allow you to populate paths.path.[http-verb].requestBody.content.[content-type].example and the response example in Swagger UI with custom, realistic data instead of autogenerated placeholders.

    As of version 5.0.0-beta, XML examples are also supported.

  6. Add request and response headers via filters

    master

    Use these filters to inject headers into the Swagger documentation:

    • Add a request header: Use AddHeaderOperationFilter to add a specific string to all requests (e.g., a correlationId).
    • Add a response header: Use AddResponseHeadersFilter to specify response headers for operations.
  7. Configure SecurityRequirementsOperationFilter for OAuth2

    master

    To show a padlock icon in Swagger-UI and automatically add 401/403 responses to operations marked with [Authorize], use the SecurityRequirementsOperationFilter.

    1. Define your security scheme (e.g., OAuth2/Bearer) in AddSwaggerGen.
    2. Register the operation filter.

    By default, the filter adds 401 and 403 status codes to any action with an [Authorize] attribute. To disable this behavior, pass false to the constructor.

    services.AddSwaggerGen(c =>
    {
        c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
        {
            Description = "Standard Authorization header using the Bearer scheme.",
            In = ParameterLocation.Header,
            Name = "Authorization",
            Type = SecuritySchemeType.ApiKey
        });
    
        // Add security information to each operation
        c.OperationFilter<SecurityRequirementsOperationFilter>();
        
        // OR: Disable automatic 401/403 addition
        // c.OperationFilter<SecurityRequirementsOperationFilter>(false);
    });
  8. Configure Swashbuckle filters in Startup.cs

    master

    To use the filters, you must register them within the AddSwaggerGen configuration in your ConfigureServices method.

    Note the version-specific syntax for Request and Response examples:

    • Swashbuckle < 3.0: Use c.OperationFilter<ExamplesOperationFilter>();
    • Swashbuckle 3.0: Use c.AddSwaggerExamples(services.BuildServiceProvider());
    • Swashbuckle > 4.0: Use c.ExampleFilters();
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
            
            // Enable Request/Response examples (for Swashbuckle > 4.0)
            c.ExampleFilters();
            
            // Add a request header (e.g., correlationId)
            c.OperationFilter<AddHeaderOperationFilter>("correlationId", "Correlation Id for the request", false);
    
            // Add response headers
            c.OperationFilter<AddResponseHeadersFilter>();
    
            // Add (Auth) to summary (requires IncludeXmlComments to be called first)
            c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, "WebApi.xml"));
            c.OperationFilter<AppendAuthorizeToSummaryOperationFilter>();
    
            // Add security info for OAuth2
            c.OperationFilter<SecurityRequirementsOperationFilter>();
            c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
            {
                Description = "Standard Authorization header using the Bearer scheme. Example: \"bearer {token}\"",
                In = ParameterLocation.Header,
                Name = "Authorization",
                Type = SecuritySchemeType.ApiKey
            });
        });
    }
  9. Install Swashbuckle.AspNetCore.Filters via NuGet

    master

    Install the Swashbuckle.AspNetCore.Filters NuGet package. Ensure you select the version compatible with your Swashbuckle.AspNetCore version:

    Swashbuckle.AspNetCore versionRequired Package Version
    1.0.0 - 2.5.0Swashbuckle.AspNetCore.Examples
    3.0.0Swashbuckle.AspNetCore.Filters
    4.0.0 and aboveSwashbuckle.AspNetCore.Filters (>= 4.5.1)
    5.0.0-beta and aboveSwashbuckle.AspNetCore.Filters (>= 5.0.0-beta)
    dotnet add package Swashbuckle.AspNetCore.Filters
  10. Add response body examples using IExamplesProvider

    master

    To add examples to API responses, implement IExamplesProvider<T> where T is the return type.

    Automatic Annotation: Works if the action return type is clearly defined (e.g., ActionResult<T> or T).

    Manual Annotation: Use the [SwaggerResponseExample(statusCode, typeof(ExampleClass))] attribute to explicitly link a provider to a specific HTTP status code. This overrides automatic detection.

    // Implementation
    public class CountryExamples : IExamplesProvider<List<Country>>
    {
        public List<Country> GetExamples()
        {
            return new List<Country> { new Country { Code = "AA", Name = "Test" } };
        }
    }
    
    // Usage
    [SwaggerResponse(200, "The list of countries", typeof(IEnumerable<Country>))]
    [SwaggerResponseExample(200, typeof(CountryExamples))]
    public async Task<HttpResponseMessage> Get(string lang)
  11. Use Dependency Injection in Examples

    master

    If your examples need to access services (e.g., reading data from a database or checking the environment), you can use constructor injection in your IExamplesProvider implementation.

    1. Implement IExamplesProvider with the required dependencies in the constructor.
    2. Register the examples using the appropriate extension method.
    internal class PersonRequestExample : IExamplesProvider
    {
        private readonly IHostingEnvironment _env;
    
        public PersonRequestExample(IHostingEnvironment env)
        {
            _env = env;
        }
    
        public object GetExamples()
        {
            return new PersonRequest 
            { 
                Age = 24, 
                FirstName = _env.IsDevelopment() ? "Development" : "Production", 
                Income = null 
            };
        }
    }
  12. Include Authorization details in Swagger Summary

    master

    To ensure that authorization requirements (like policies or roles) are visible in the Swagger documentation summary, use the [Authorize] attribute on your Controller or Action. The filter will extract the policy or role names and include them in the generated summary.

    [Authorize]
    public class ValuesController : Controller
    {
        [Authorize("Customer")]
        public PersonResponse GetPerson([FromBody]PersonRequest personRequest)
        {
            // ...
        }
    }