### Implement IMultipleExamplesProvider for Multiple Examples Source: https://github.com/mattfrear/swashbuckle.aspnetcore.filters/blob/master/README.md Implement IMultipleExamplesProvider to provide multiple examples for an API response. Use SwaggerExample.Create and yield return for each example. ```csharp public class DeliveryOptionsSearchModelExample : IMultipleExamplesProvider { public IEnumerable> GetExamples() { // An example without a summary. yield return SwaggerExample.Create( "Great Britain", "Here's an optional description" // optional description - Markdown is supported new DeliveryOptionsSearchModel { Lang = "en-GB", Currency = "GBP", Address = new AddressModel { Address1 = "1 Gwalior Road", Locality = "London", Country = "GB", PostalCode = "SW15 1NP" } } ); // An example with a summary. yield return SwaggerExample.Create( "United States", "A minor former colony of Great Britain", new DeliveryOptionsSearchModel { Lang = "en-US", Currency = "USD", Address = new AddressModel { Address1 = "123 Main Street", Locality = "New York", Country = "US", PostalCode = "10001" } }, ); } } ``` -------------------------------- ### Add Product Name Example with XML Comments Source: https://github.com/mattfrear/swashbuckle.aspnetcore.filters/blob/master/README.md Use XML comments with the tag to provide sample values for properties. This works for request and response examples, including query and route parameters. ```csharp public class Product { /// /// The name of the product /// /// Men's basketball shoes public string Name { get; set; } ``` -------------------------------- ### Implement Single Example Provider (Request) Source: https://context7.com/mattfrear/swashbuckle.aspnetcore.filters/llms.txt Implement IExamplesProvider to provide a single example for request types. This example is automatically associated with endpoints using the matching type. ```csharp using Swashbuckle.AspNetCore.Filters; // Model classes public class PersonRequest { public Title Title { get; set; } public int Age { get; set; } public string FirstName { get; set; } public decimal? Income { get; set; } } public class PersonResponse { public int Id { get; set; } public Title Title { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public int Age { get; set; } public decimal? Income { get; set; } } public enum Title { None = 0, Dr, Miss, Mr, Mrs, Ms } // Request example provider - automatically used for PersonRequest parameters public class PersonRequestExample : IExamplesProvider { public PersonRequest GetExamples() { return new PersonRequest { Title = Title.Mr, Age = 24, FirstName = "Dave", Income = null }; } } ``` -------------------------------- ### Implement IExamplesProvider for Runtime Examples Source: https://github.com/mattfrear/swashbuckle.aspnetcore.filters/blob/master/README.md Implement the IExamplesProvider interface to generate examples for input models at runtime. This is an alternative to XML comments when runtime generation or XML request examples are needed. ```csharp [HttpPost] public async Task DeliveryOptionsForAddress([FromBody]DeliveryOptionsSearchModel search) ``` ```csharp public class DeliveryOptionsSearchModelExample : IExamplesProvider { public DeliveryOptionsSearchModel GetExamples() { return new DeliveryOptionsSearchModel { Lang = "en-GB", Currency = "GBP", Address = new AddressModel { Address1 = "1 Gwalior Road", Locality = "London", Country = "GB", PostalCode = "SW15 1NP" } }; } } ``` -------------------------------- ### Implement Single Example Provider (Response) Source: https://context7.com/mattfrear/swashbuckle.aspnetcore.filters/llms.txt Implement IExamplesProvider to provide a single example for response types. This example is automatically associated with endpoints using the matching type. ```csharp using Swashbuckle.AspNetCore.Filters; // Model classes public class PersonRequest { public Title Title { get; set; } public int Age { get; set; } public string FirstName { get; set; } public decimal? Income { get; set; } } public class PersonResponse { public int Id { get; set; } public Title Title { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public int Age { get; set; } public decimal? Income { get; set; } } public enum Title { None = 0, Dr, Miss, Mr, Mrs, Ms } // Response example provider - automatically used for PersonResponse return types public class PersonResponseExample : IExamplesProvider { public PersonResponse GetExamples() { return new PersonResponse { Id = 123, Title = Title.Dr, FirstName = "John", LastName = "Doe", Age = 27, Income = null }; } } ``` -------------------------------- ### Dependency Injection for Dynamic Example Providers Source: https://context7.com/mattfrear/swashbuckle.aspnetcore.filters/llms.txt Implement IExamplesProvider for dynamic example generation, supporting constructor injection of services like IWebHostEnvironment and IConfiguration. Register providers using AddSwaggerExamplesFromAssemblyOf. ```csharp using Swashbuckle.AspNetCore.Filters; public class PersonRequestDependencyInjectionExample : IExamplesProvider { private readonly IWebHostEnvironment _hostingEnvironment; private readonly IConfiguration _configuration; public PersonRequestDependencyInjectionExample( IWebHostEnvironment hostingEnvironment, IConfiguration configuration) { _hostingEnvironment = hostingEnvironment; _configuration = configuration; } public PersonRequest GetExamples() { var defaultAge = _configuration.GetValue("DefaultExampleAge", 25); return new PersonRequest { Title = Title.Mr, Age = defaultAge, FirstName = $"Dave ({_hostingEnvironment.EnvironmentName})", Income = null }; } } // Registration - use FromAssemblyOf for automatic DI registration services.AddSwaggerExamplesFromAssemblyOf(); // Alternative registration methods services.AddSwaggerExamplesFromAssemblyOf(typeof(PersonRequestExample), typeof(OtherExample)); services.AddSwaggerExamplesFromAssemblies(Assembly.GetEntryAssembly()); ``` -------------------------------- ### Use SwaggerRequestExampleAttribute for Explicit Request Examples Source: https://context7.com/mattfrear/swashbuckle.aspnetcore.filters/llms.txt Use this attribute to explicitly specify which example provider to use for a request body. Overrides automatic detection. This example shows how to link a controller action to a specific example provider. ```csharp using Swashbuckle.AspNetCore.Filters; [ApiController] [Route("api/[controller]")] public class ValuesController : ControllerBase { // Explicit request example using attribute [HttpPost("person")] [SwaggerRequestExample(typeof(PersonRequest), typeof(PersonRequestExample))] [ProducesResponseType(typeof(PersonResponse), 200)] public PersonResponse PostPerson([FromBody] PersonRequest personRequest) { return new PersonResponse { Id = 1, FirstName = personRequest.FirstName }; } // Multiple request examples [HttpPost("anyone")] [SwaggerRequestExample(typeof(PersonRequest), typeof(PersonRequestMultipleExamples))] [ProducesResponseType(typeof(PersonResponse), 200)] public PersonResponse PostAnyone([FromBody] PersonRequest personRequest) { return new PersonResponse { Id = 1, FirstName = personRequest.FirstName }; } // List request example - provider returns single T, displayed as list [HttpPost("listperson")] [SwaggerRequestExample(typeof(IEnumerable), typeof(ListPeopleRequestExample))] [ProducesResponseType(typeof(IEnumerable), 200)] public IEnumerable PostPersonList([FromBody] List peopleRequest) { return new[] { new PersonResponse { Id = 1, FirstName = "Sally" } }; } } // Example provider for list items public class ListPeopleRequestExample : IExamplesProvider { public PeopleRequest GetExamples() { return new PeopleRequest { Title = Title.Mr, Age = 24, FirstName = "Dave in a list" }; } } ``` -------------------------------- ### Registering Swagger Example Filters Source: https://github.com/mattfrear/swashbuckle.aspnetcore.filters/blob/master/README.md Register your custom example classes with the ServiceProvider when using the Request and Response example filters. This is required if `c.ExampleFilters()` has been called. ```csharp services.AddSwaggerExamplesFromAssemblyOf(); ``` ```csharp services.AddSwaggerExamplesFromAssemblyOf(typeof(MyExample)); ``` ```csharp services.AddSwaggerExamplesFromAssemblies(Assembly.GetEntryAssembly()); ``` -------------------------------- ### Implement IExamplesProvider for Request Examples Source: https://github.com/mattfrear/swashbuckle.aspnetcore.filters/blob/master/README.md Implement the `IExamplesProvider` interface to generate example data for a specific model type. The `GetExamples` method should return an instance of the model specified in the `SwaggerRequestExample` attribute. ```csharp public class DeliveryOptionsSearchModelExample : IExamplesProvider { public DeliveryOptionsSearchModel GetExamples() { return new DeliveryOptionsSearchModel { Lang = "en-GB", Currency = "GBP", Address = new AddressModel { Address1 = "1 Gwalior Road", Locality = "London", Country = "GB", PostalCode = "SW15 1NP" }, Items = new[] { new ItemModel { ItemId = "ABCD", ItemType = ItemType.Product, Price = 20, Quantity = 1, RestrictedCountries = new[] { "US" } } } }; } } ``` -------------------------------- ### Implement IMultipleExamplesProvider for Custom Examples Source: https://context7.com/mattfrear/swashbuckle.aspnetcore.filters/llms.txt Implement this interface to provide multiple named examples for a single type. Useful for demonstrating different scenarios in the Swagger UI dropdown. Supports Markdown in descriptions. ```csharp using Swashbuckle.AspNetCore.Filters; public class PersonRequestMultipleExamples : IMultipleExamplesProvider { public IEnumerable> GetExamples() { // Example with name, summary, description (Markdown supported), and value yield return SwaggerExample.Create( "Dave", "Posts Dave", "This description is rendered as _Markdown_ by *SwaggerUI*", new PersonRequest { FirstName = "Dave", Title = Title.Mr } ); // Example with Markdown description yield return SwaggerExample.Create( "Angela", "Let's add Angela", @" ## Markdown rules! This is a great feature for longer descriptions. ", new PersonRequest { FirstName = "Angela", Title = Title.Dr } ); // Example without description yield return SwaggerExample.Create( "Michael", "And the last example", new PersonRequest { FirstName = "Michael", Income = 321.7m } ); // Null example yield return SwaggerExample.Create("Null guy", null); } } public class PersonResponseMultipleExamples : IMultipleExamplesProvider { public IEnumerable> GetExamples() { yield return new SwaggerExample { Name = "John", Summary = "can return John", Description = "which is a really *cool* feature.", Value = new PersonResponse { Id = 123, Title = Title.Dr, FirstName = "John", LastName = "Doe", Age = 27 } }; yield return new SwaggerExample { Name = "Angela", Summary = "or Angela", Description = "which is also _great_!", Value = new PersonResponse { Id = 124, Title = Title.Miss, FirstName = "Angela", LastName = "Doe", Age = 28 } }; } } ``` -------------------------------- ### Implement IExamplesProvider for Single Example Source: https://github.com/mattfrear/swashbuckle.aspnetcore.filters/blob/master/README.md Implement IExamplesProvider to generate example data for a specific response type. This is used by SwaggerResponseExample. ```csharp public class CountryExamples : IExamplesProvider> { public List GetExamples() { return new List { new Country { Code = "AA", Name = "Test Country" }, new Country { Code = "BB", Name = "And another" } }; } } ``` -------------------------------- ### Implement IExamplesProvider with Constructor Injection Source: https://github.com/mattfrear/swashbuckle.aspnetcore.filters/blob/master/README.md Use constructor injection to provide dependencies like IHostingEnvironment to your examples provider. This allows for dynamic example generation based on application environment. ```csharp 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 }; } } ``` -------------------------------- ### Implement IExamplesProvider for List Item Type Source: https://github.com/mattfrear/swashbuckle.aspnetcore.filters/blob/master/README.md Provide example data for the individual item type within a list request. The `GetExamples` method should return a single instance of the item type. ```csharp public class ListPeopleRequestExample : IExamplesProvider { public PeopleRequest GetExamples() { return new PeopleRequest { Title = Title.Mr, Age = 24, FirstName = "Dave in a list", Income = null }; } } ``` -------------------------------- ### Register Swagger Examples from Assembly Source: https://github.com/mattfrear/swashbuckle.aspnetcore.filters/blob/master/README.md Register all IExamplesProvider implementations found within a specified assembly. This is the recommended approach for automatic discovery of examples. ```csharp services.AddSwaggerExamplesFromAssemblyOf(); ``` ```csharp services.AddSwaggerExamplesFromAssemblyOf(typeof(PersonRequestExample)); ``` ```csharp services.AddSwaggerExamplesFromAssemblies(Assembly.GetEntryAssembly()); ``` -------------------------------- ### Register Example Providers and Enable Filters Source: https://context7.com/mattfrear/swashbuckle.aspnetcore.filters/llms.txt Register example providers from assemblies or specific types, and enable filters in SwaggerGen. Recommended for automatic assembly scanning. ```csharp using Swashbuckle.AspNetCore.Filters; using System.Reflection; var builder = WebApplication.CreateBuilder(args); // Method 1: Register from assembly containing specific type (recommended) builder.Services.AddSwaggerExamplesFromAssemblyOf(); // Method 2: Register from multiple types' assemblies builder.Services.AddSwaggerExamplesFromAssemblyOf(typeof(PersonRequestExample), typeof(OrderRequestExample)); // Method 3: Register from assemblies directly builder.Services.AddSwaggerExamplesFromAssemblies( Assembly.GetEntryAssembly(), Assembly.Load("MyCompany.Examples") ); // Method 4: Manual registration (if you need fine-grained control) builder.Services.AddSwaggerExamples(); builder.Services.AddSingleton(); builder.Services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" }); // Standard filter registration order c.ExampleFilters(); // Alternative: Prioritize explicitly defined examples over automatic ones // c.ExampleFilters_PrioritizingExplicitlyDefinedExamples(); }); ``` -------------------------------- ### Controller with Automatic Example Detection Source: https://context7.com/mattfrear/swashbuckle.aspnetcore.filters/llms.txt A controller demonstrating how PersonRequestExample and PersonResponseExample are automatically applied to the API endpoint for request and response examples. ```csharp // Controller using automatic example detection [ApiController] [Route("api/[controller]")] public class PersonController : ControllerBase { // PersonRequestExample and PersonResponseExample are automatically applied [HttpPost] [ProducesResponseType(typeof(PersonResponse), 200)] public PersonResponse CreatePerson([FromBody] PersonRequest request) { return new PersonResponse { Id = 1, FirstName = request.FirstName }; } } ``` -------------------------------- ### Specify Manual Response Examples with SwaggerResponseExampleAttribute Source: https://context7.com/mattfrear/swashbuckle.aspnetcore.filters/llms.txt Use this attribute to explicitly define example providers for response types at specific HTTP status codes. Ensure the example provider class implements IExamplesProvider. ```csharp using Swashbuckle.AspNetCore.Filters; using Swashbuckle.AspNetCore.Annotations; [ApiController] [Route("api/[controller]")] [SwaggerResponse(404, type: typeof(ErrorResponse), description: "Could not find the person")] [SwaggerResponseExample(404, typeof(NotFoundResponseExample))] // Controller-level example public class ValuesController : ControllerBase { [HttpGet("person/{personId}")] [SwaggerResponse(200, type: typeof(PersonResponse), description: "Successfully found the person")] [SwaggerResponseExample(200, typeof(PersonResponseExample))] [SwaggerResponse(500, type: null, description: "There was an unexpected error")] [SwaggerResponseExample(500, typeof(InternalServerResponseExample))] public PersonResponse GetPerson(int personId) { return new PersonResponse { Id = personId, FirstName = "Dave" }; } // Multiple response examples [HttpPost("anyone")] [SwaggerResponse(200, type: typeof(PersonResponse), description: "Successfully added the person")] [SwaggerResponseExample(200, typeof(PersonResponseMultipleExamples))] public PersonResponse PostAnyone([FromBody] PersonRequest personRequest) { return new PersonResponse { Id = 1, FirstName = "Dave", LastName = "Multi" }; } } // Error response examples public class NotFoundResponseExample : IExamplesProvider { public ErrorResponse GetExamples() { return new ErrorResponse { Message = "Person not found", ErrorCode = "PERSON_NOT_FOUND" }; } } public class InternalServerResponseExample : IExamplesProvider { public ErrorResponse GetExamples() { return new ErrorResponse { Message = "An unexpected error occurred", ErrorCode = "INTERNAL_ERROR" }; } } ``` -------------------------------- ### SwaggerResponseExampleAttribute - Manual Response Example Source: https://context7.com/mattfrear/swashbuckle.aspnetcore.filters/llms.txt Use this attribute to explicitly specify example providers for response types at specific HTTP status codes. This allows for detailed examples of successful and error responses. ```APIDOC ## GET /api/values/person/{personId} ### Description Retrieves a specific person's details based on their ID. ### Method GET ### Endpoint /api/values/person/{personId} ### Parameters #### Path Parameters - **personId** (int) - Required - The unique identifier of the person. ### Response #### Success Response (200) - **Id** (int) - The unique identifier of the person. - **FirstName** (string) - The first name of the person. #### Response Example ```json { "Id": 123, "FirstName": "Dave" } ``` #### Error Response (404) - **Message** (string) - Description of the error. - **ErrorCode** (string) - A code representing the type of error. #### Response Example ```json { "Message": "Person not found", "ErrorCode": "PERSON_NOT_FOUND" } ``` #### Error Response (500) - **Message** (string) - Description of the error. - **ErrorCode** (string) - A code representing the type of error. #### Response Example ```json { "Message": "An unexpected error occurred", "ErrorCode": "INTERNAL_ERROR" } ``` ``` ```APIDOC ## POST /api/values/anyone ### Description Adds a new person to the system with provided details. ### Method POST ### Endpoint /api/values/anyone ### Parameters #### Request Body - **FirstName** (string) - Required - The first name of the person. - **LastName** (string) - Required - The last name of the person. ### Response #### Success Response (200) - **Id** (int) - The unique identifier of the newly created person. - **FirstName** (string) - The first name of the person. - **LastName** (string) - The last name of the person. #### Response Example ```json { "Id": 1, "FirstName": "Dave", "LastName": "Multi" } ``` ``` -------------------------------- ### Enable SerializeAsV2 for Request Examples Source: https://github.com/mattfrear/swashbuckle.aspnetcore.filters/blob/master/README.md If using the Request example filter and serializing as Swagger 2.0, you must explicitly configure `SerializeAsV2` to be true. ```csharp services.Configure(c => c.SerializeAsV2 = true); ``` -------------------------------- ### Add Example for Primitive Query Parameter Source: https://github.com/mattfrear/swashbuckle.aspnetcore.filters/blob/master/README.md Demonstrates how to add an example for a primitive type used as a query parameter using XML comments. This feature is available after a specific Swashbuckle.AspNetCore release. ```csharp /// The product id [HttpGet("{id}")] public Product GetById(int id) ``` -------------------------------- ### Configure Services for Swagger Filters Source: https://github.com/mattfrear/swashbuckle.aspnetcore.filters/blob/master/README.md Configure Swagger generation services in `Startup.cs`. This includes enabling example filters, adding custom operation filters for headers and authorization summaries, and including XML comments. ```csharp // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddMvc(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" }); // [SwaggerRequestExample] & [SwaggerResponseExample] // version < 3.0 like this: c.OperationFilter(); // version 3.0 like this: c.AddSwaggerExamples(services.BuildServiceProvider()); // version > 4.0 like this: c.ExampleFilters(); c.OperationFilter("correlationId", "Correlation Id for the request", false); // adds any string you like to the request headers - in this case, a correlation id c.OperationFilter(); // [SwaggerResponseHeader] var filePath = Path.Combine(AppContext.BaseDirectory, "WebApi.xml"); c.IncludeXmlComments(filePath); // standard Swashbuckle functionality, this needs to be before c.OperationFilter() c.OperationFilter(); // Adds "(Auth)" to the summary so that you can see which endpoints have Authorization // or use the generic method, e.g. c.OperationFilter>(); // add Security information to each operation for OAuth2 c.OperationFilter(); // or use the generic method, e.g. c.OperationFilter>(); // if you're using the SecurityRequirementsOperationFilter, you also need to tell Swashbuckle you're using OAuth2 c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme { Description = "Standard Authorization header using the Bearer scheme. Example: \"bearer {token}\"", In = ParameterLocation.Header, Name = "Authorization", Type = SecuritySchemeType.ApiKey }); }); } ``` -------------------------------- ### Example JSON Response Structure Source: https://github.com/mattfrear/swashbuckle.aspnetcore.filters/blob/master/README.md This JSON structure illustrates how an example response object is represented in the Swagger/OpenAPI document for a given media type. ```json "responses": { "200": { "description": "Success", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Pet" }, "example": "{\r\n \"name\": \"Lassie\",\r\n \"type\": \"Dog\",\r\n \"color\": \"Black\",\r\n \"gender\": \"Femail\",\r\n \"breed\": \"Collie\" \r\n}" }, ``` -------------------------------- ### Annotate List Request Examples Source: https://github.com/mattfrear/swashbuckle.aspnetcore.filters/blob/master/README.md For `List` requests, apply `SwaggerRequestExample` to the type `T`. The `IExamplesProvider` should return a single instance of `T`, not a `List`. ```csharp [SwaggerRequestExample(typeof(PeopleRequest), typeof(ListPeopleRequestExample))] public IEnumerable GetPersonList([FromBody]List peopleRequest) ``` -------------------------------- ### Annotate Method with SwaggerResponseExample Source: https://github.com/mattfrear/swashbuckle.aspnetcore.filters/blob/master/README.md Decorate methods with SwaggerResponseExample to provide custom response examples. Manual annotations override automatic ones. ```csharp [SwaggerResponse(200, "The list of countries", typeof(IEnumerable))] // or, like this [ProducesResponseType(typeof(IEnumerable), 200)] [SwaggerResponseExample(200, typeof(CountryExamples))] [SwaggerResponse(400, type: typeof(IEnumerable))] public async Task Get(string lang) ``` -------------------------------- ### Decorate Controller Method with SwaggerRequestExample Source: https://github.com/mattfrear/swashbuckle.aspnetcore.filters/blob/master/README.md Use the `SwaggerRequestExample` attribute to explicitly define the type and example provider for a request body. This method overrides any automatic annotations. ```csharp [HttpPost] [SwaggerRequestExample(typeof(DeliveryOptionsSearchModel), typeof(DeliveryOptionsSearchModelExample))] public async Task DeliveryOptionsForAddress([FromBody]DeliveryOptionsSearchModel search) ``` -------------------------------- ### Configure Swashbuckle.AspNetCore.Filters Source: https://context7.com/mattfrear/swashbuckle.aspnetcore.filters/llms.txt Register services and enable filters in your Swagger configuration. This includes adding example providers and operation filters for security and headers. ```csharp using Swashbuckle.AspNetCore.Filters; var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); builder.Services.AddEndpointsApiExplorer(); // Register example providers from your assembly builder.Services.AddSwaggerExamplesFromAssemblyOf(); builder.Services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" }); // Enable request and response example filters c.ExampleFilters(); // Add custom header to all requests c.OperationFilter("X-Correlation-Id", "Correlation Id for the request", false); // Add response headers filter c.OperationFilter(); // Add "(Auth)" to summary for endpoints with [Authorize] c.OperationFilter(); // Add security requirements for OAuth2 c.OperationFilter(); // Define OAuth2 security scheme c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme { Description = "Standard Authorization header using the Bearer scheme. Example: \"bearer {token}\"", In = ParameterLocation.Header, Name = "Authorization", Type = SecuritySchemeType.ApiKey }); }); var app = builder.Build(); app.UseSwagger(); app.UseSwaggerUI(); app.MapControllers(); app.Run(); ``` -------------------------------- ### Configure OpenAPI 2.0 (Swagger) Format Output Source: https://context7.com/mattfrear/swashbuckle.aspnetcore.filters/llms.txt Configure Swashbuckle to output the legacy Swagger 2.0 format instead of OpenAPI 3.0. Note that multiple examples are not supported in OpenAPI 2.0. ```csharp var builder = WebApplication.CreateBuilder(args); // Method 1: Configure via SwaggerOptions builder.Services.Configure(c => c.OpenApiVersion = Microsoft.OpenApi.OpenApiSpecVersion.OpenApi2_0); // Method 2: Configure in UseSwagger middleware var app = builder.Build(); app.UseSwagger(c => c.OpenApiVersion = Microsoft.OpenApi.OpenApiSpecVersion.OpenApi2_0); // Note: Multiple examples (IMultipleExamplesProvider) are not supported in OpenAPI 2.0 ``` -------------------------------- ### Packing NuGet Packages Source: https://github.com/mattfrear/swashbuckle.aspnetcore.filters/blob/master/tools/NuGet instructions.txt Create NuGet packages for the project, including symbol packages. Ensure the build configuration is set to 'Release'. ```bash dotnet pack -p:IncludeSymbols=true -p:SymbolPackageFormat=snupkg -c Release ``` -------------------------------- ### Manually Register IExamplesProvider Source: https://github.com/mattfrear/swashbuckle.aspnetcore.filters/blob/master/README.md Manually register your IExamplesProvider class as a singleton service when using the generic AddSwaggerExamples() method. This is an alternative to assembly scanning. ```csharp services.AddSingleton(); ``` -------------------------------- ### Pushing Main NuGet Package Source: https://github.com/mattfrear/swashbuckle.aspnetcore.filters/blob/master/tools/NuGet instructions.txt Publish the main Swashbuckle.AspNetCore.Filters NuGet package to a specified source using your API key. Navigate to the package directory first. ```bash cd src\Swashbuckle.AspNetCore.Filters\bin\Release nuget push Swashbuckle.AspNetCore.Filters.7.0.0.nupkg MySecretNuGetApiKeyHere -Source https://api.nuget.org/v3/index.json ``` -------------------------------- ### Tagging a Release Source: https://github.com/mattfrear/swashbuckle.aspnetcore.filters/blob/master/tools/NuGet instructions.txt Create an annotated Git tag for the release. This is typically done after updating version information and committing changes. ```bash git tag -a v1.2.5 -m 'Fix issue #89' ``` -------------------------------- ### Pushing Abstractions NuGet Package Source: https://github.com/mattfrear/swashbuckle.aspnetcore.filters/blob/master/tools/NuGet instructions.txt Publish the Swashbuckle.AspNetCore.Filters.Abstractions NuGet package to a specified source using your API key. Navigate to the package directory first. ```bash cd src\Swashbuckle.AspNetCore.Filters.Abstractions\bin\Release nuget push Swashbuckle.AspNetCore.Filters.Abstrations.7.0.0.nupkg MySecretNuGetApiKeyHere -Source https://api.nuget.org/v3/index.json ``` -------------------------------- ### Serialize Swagger in Swagger 2.0 Format Source: https://github.com/mattfrear/swashbuckle.aspnetcore.filters/blob/master/README.md Configure Swashbuckle.AspNetCore to output the swagger.json in the legacy Swagger 2.0 format. This can be done either by configuring the `UseSwagger` middleware or by configuring `SwaggerOptions`. ```csharp app.UseSwagger(c => c.OpenApiVersion = Microsoft.OpenApi.OpenApiSpecVersion.OpenApi2_0); ``` ```csharp builder.Services.Configure(c => c.OpenApiVersion = Microsoft.OpenApi.OpenApiSpecVersion.OpenApi2_0); ``` -------------------------------- ### Pushing Tags to Remote Source: https://github.com/mattfrear/swashbuckle.aspnetcore.filters/blob/master/tools/NuGet instructions.txt Push all local tags to the remote repository to ensure they are backed up and visible. This command includes the newly created tag. ```bash git push --follow-tags ``` -------------------------------- ### Apply Authorize Attribute with Policy to Action Source: https://github.com/mattfrear/swashbuckle.aspnetcore.filters/blob/master/README.md Apply the [Authorize] attribute with a specific policy to an action method to enforce authorization. This policy will be included in the Swagger summary. ```csharp [Authorize("Customer")] public PersonResponse GetPerson([FromBody]PersonRequest personRequest) ``` -------------------------------- ### Apply Authorize Attribute with Roles to Action Source: https://github.com/mattfrear/swashbuckle.aspnetcore.filters/blob/master/README.md Apply the [Authorize] attribute with specified roles to an action method to enforce role-based access control. These roles will be included in the Swagger summary. ```csharp [Authorize(Roles = "Customer")] public PersonResponse GetPerson([FromBody]PersonRequest personRequest) ``` -------------------------------- ### Apply Authorize Attribute to Controller Source: https://github.com/mattfrear/swashbuckle.aspnetcore.filters/blob/master/README.md Apply the [Authorize] attribute to a controller class to secure all its actions by default. This will be reflected in the Swagger summary. ```csharp [Authorize] public class ValuesController : Controller ``` -------------------------------- ### Append Authorization Info to Swagger Summaries Source: https://context7.com/mattfrear/swashbuckle.aspnetcore.filters/llms.txt Configure SwaggerGen to include authorization policy and role information in operation summaries. Ensure XML comments are included before this filter. ```csharp // In Startup.cs or Program.cs services.AddSwaggerGen(c => { // Include XML comments before this filter var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); // Add authorization info to summaries c.OperationFilter(); }); [ApiController] [Authorize] [Route("api/[controller]")] public class ValuesController : ControllerBase { /// /// Gets all people /// /// Summary shows: "Gets all people (Auth policies: Customer)" [HttpGet] [Authorize("Customer")] public IEnumerable GetPeople() => Array.Empty(); /// /// Gets admin data /// /// Summary shows: "Gets admin data (Auth roles: Admin)" [HttpGet("admin")] [Authorize(Roles = "Admin")] public string GetAdmin() => "Admin"; } ``` -------------------------------- ### Add Global Request Headers with AddHeaderOperationFilter Source: https://context7.com/mattfrear/swashbuckle.aspnetcore.filters/llms.txt This operation filter adds custom header parameters to all API operations, which is useful for requirements like correlation IDs or tenant identifiers. Configure it in your Startup.cs or Program.cs. ```csharp // In Startup.cs or Program.cs services.AddSwaggerGen(c => { // Add correlation ID header to all requests (optional parameter) c.OperationFilter("X-Correlation-Id", "Correlation Id for request tracing", false); // Add required tenant header c.OperationFilter("X-Tenant-Id", "Tenant identifier", true); }); // The header appears in Swagger UI for every endpoint: // curl -X POST "https://api.example.com/api/person" \ // -H "X-Correlation-Id: 550e8400-e29b-41d4-a716-446655440000" \ // -H "X-Tenant-Id: tenant-123" \ // -H "Content-Type: application/json" \ // -d '{"title": 3, "age": 24, "firstName": "Dave"}' ``` -------------------------------- ### Add Custom Request Header Filter Source: https://github.com/mattfrear/swashbuckle.aspnetcore.filters/blob/master/README.md Enable a filter to add a custom input box for a request header to every controller action. Specify the header's name, description, and whether it's required. ```csharp services.AddSwaggerGen(c => { // Add custom header parameter c.OperationFilter("X-Custom-Header", "My Custom Header", true); }); ``` -------------------------------- ### Automatic ResponseType Annotation Source: https://github.com/mattfrear/swashbuckle.aspnetcore.filters/blob/master/README.md When the return type of an action is obvious, Swashbuckle.AspNetCore can automatically annotate it without explicit `ProducesResponseType` or `SwaggerResponse` attributes. ```csharp public async Task>> Get(string lang) ``` ```csharp // or public ActionResult> Get(string lang) ``` ```csharp // or public IEnumerable Get(string lang) ``` -------------------------------- ### Add OAuth2 Security Definition to Swagger Source: https://github.com/mattfrear/swashbuckle.aspnetcore.filters/blob/master/README.md Configure SwaggerGen to add an OAuth2 security definition. This is necessary for Swagger-UI to render an 'Authorize' button. ```csharp services.AddSwaggerGen(c => { c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme { Description = "Standard Authorization header using the Bearer scheme. Example: \"bearer {token}\"", In = ParameterLocation.Header, Name = "Authorization", Type = SecuritySchemeType.ApiKey }); ``` -------------------------------- ### Enable SecurityRequirementsOperationFilter for OAuth2 Source: https://github.com/mattfrear/swashbuckle.aspnetcore.filters/blob/master/README.md Enable the SecurityRequirementsOperationFilter to automatically add security information to operations that require authorization. This renders a padlock icon in Swagger-UI. ```csharp // add Security information to each operation for OAuth2 c.OperationFilter(); ``` -------------------------------- ### Disable Default 401/403 Responses in SecurityRequirementsOperationFilter Source: https://github.com/mattfrear/swashbuckle.aspnetcore.filters/blob/master/README.md Configure the SecurityRequirementsOperationFilter with 'false' to prevent it from automatically adding 401 and 403 status codes to operations marked with [Authorize]. ```csharp c.OperationFilter(false); ``` -------------------------------- ### AddHeaderOperationFilter - Global Request Headers Source: https://context7.com/mattfrear/swashbuckle.aspnetcore.filters/llms.txt Globally adds custom header parameters to all API operations, which is beneficial for cross-cutting concerns like correlation IDs or tenant identifiers. ```APIDOC ## Global Request Headers ### Description This section describes how to configure global request headers that will be applied to all API operations. ### Method Applies to all HTTP methods (GET, POST, PUT, DELETE, etc.). ### Endpoint All endpoints. ### Parameters #### Request Headers - **X-Correlation-Id** (string) - Optional - Correlation Id for request tracing. - **X-Tenant-Id** (string) - Required - Tenant identifier. ### Request Example (using curl) ```bash curl -X POST "https://api.example.com/api/person" \ -H "X-Correlation-Id: 550e8400-e29b-41d4-a716-446655440000" \ -H "X-Tenant-Id: tenant-123" \ -H "Content-Type: application/json" \ -d '{"title": 3, "age": 24, "firstName": "Dave"}' ``` ``` -------------------------------- ### Add OAuth2 Security Requirements to Swagger Source: https://context7.com/mattfrear/swashbuckle.aspnetcore.filters/llms.txt Configure SwaggerGen to automatically add security requirements and optional 401/403 responses for endpoints with [Authorize] attributes. Define the security scheme, such as JWT Bearer. ```csharp // In Startup.cs or Program.cs services.AddSwaggerGen(c => { // Add with default settings (includes 401/403 responses) c.OperationFilter(); // Or without automatic 401/403 responses c.OperationFilter(false); // Or with custom security scheme name c.OperationFilter(true, "bearer"); // Define the security scheme c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme { Description = "JWT Authorization header using the Bearer scheme.", In = ParameterLocation.Header, Name = "Authorization", Type = SecuritySchemeType.ApiKey }); }); // Controller with authorization [ApiController] [Authorize] // All endpoints in this controller require authorization [Route("api/[controller]")] public class SecureController : ControllerBase { [HttpGet("public")] [AllowAnonymous] // This endpoint is public public string GetPublic() => "Public data"; [HttpGet("private")] public string GetPrivate() => "Private data"; [HttpGet("admin")] [Authorize("AdminPolicy")] // Requires specific policy public string GetAdmin() => "Admin data"; [HttpGet("customer")] [Authorize(Roles = "Customer")] // Requires specific role public string GetCustomer() => "Customer data"; } ``` -------------------------------- ### Add SwaggerResponseHeader Attributes Source: https://github.com/mattfrear/swashbuckle.aspnetcore.filters/blob/master/README.md Use SwaggerResponseHeader attributes on controller actions to specify custom response headers. You can define the status code, header name, type, description, and format. ```csharp [SwaggerResponseHeader(StatusCodes.Status200OK, "Location", "string", "Location of the newly created resource")] [SwaggerResponseHeader(200, "ETag", "string", "An ETag of the resource")] [SwaggerResponseHeader(429, "Retry-After", "integer", "Indicates how long to wait before making a new request.", "int32")] [SwaggerResponseHeader(new int[] { 200, 401, 403, 404 }, "CustomHeader", "string", "A custom header")] public IHttpActionResult GetPerson(PersonRequest personRequest) ``` -------------------------------- ### Declare Custom Response Headers with SwaggerResponseHeaderAttribute Source: https://context7.com/mattfrear/swashbuckle.aspnetcore.filters/llms.txt Use this attribute to declare custom response headers for specific HTTP status codes. It can be applied to multiple status codes at the controller level or individually for each endpoint. ```csharp using Swashbuckle.AspNetCore.Filters; using Microsoft.OpenApi; [ApiController] [Route("api/[controller]")] // Apply to multiple status codes [SwaggerResponseHeader(new int[] { 200, 401, 403, 404 }, "X-Custom-Header", JsonSchemaType.String, "A custom header")] public class ValuesController : ControllerBase { [HttpPost("person")] // Single status code headers [SwaggerResponseHeader(StatusCodes.Status200OK, "Location", JsonSchemaType.String, "Location of the newly created resource")] [SwaggerResponseHeader(200, "ETag", JsonSchemaType.String, "An ETag of the resource")] [SwaggerResponseHeader(429, "Retry-After", JsonSchemaType.Integer, "Indicates how long to wait before making a new request.", "int32")] [ProducesResponseType(typeof(PersonResponse), 200)] public PersonResponse PostPerson([FromBody] PersonRequest personRequest) { Response.Headers["Location"] = "/api/values/person/123"; Response.Headers["ETag"] = "\"abc123\""; return new PersonResponse { Id = 1, FirstName = personRequest.FirstName }; } } ``` -------------------------------- ### SwaggerResponseHeaderAttribute - Custom Response Headers Source: https://context7.com/mattfrear/swashbuckle.aspnetcore.filters/llms.txt Declare custom response headers for specific HTTP status codes. This is useful for providing metadata like ETag, Location, or Retry-After. ```APIDOC ## POST /api/values/person ### Description Creates a new person resource and returns its details along with relevant headers. ### Method POST ### Endpoint /api/values/person ### Parameters #### Request Body - **FirstName** (string) - Required - The first name of the person. ### Response #### Success Response (200) - **Id** (int) - The unique identifier of the newly created person. - **FirstName** (string) - The first name of the person. #### Headers - **Location** (string) - Location of the newly created resource. - **ETag** (string) - An ETag of the resource. #### Response Example ```json { "Id": 1, "FirstName": "Dave" } ``` #### Error Response (429) #### Headers - **Retry-After** (int) - Indicates how long to wait before making a new request. #### Error Response (404) #### Headers - **X-Custom-Header** (string) - A custom header. #### Error Response (401) #### Headers - **X-Custom-Header** (string) - A custom header. #### Error Response (403) #### Headers - **X-Custom-Header** (string) - A custom header. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.