Skip to content

givtnl/Swashbuckle.AspNetCore.Filters

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Swashbuckle.AspNetCore.Filters

Build status NuGet

đź“Ł Rename to Swashbuckle.AspNetCore.Filters
This project was formerly called Swashbuckle.AspNetCore.Examples, but it has grown from there to become a grab-bag of various filters I have created (or copied) since I started used Swashbuckle in 2015. So I have renamed it.

This library contains a bunch of filters for Swashbuckle.AspNetCore.

Table of Contents

Changelog

See the CHANGELOG.md.

Where to get it

From NuGet.

Version of Swashbuckle you're using You'll want this version of this package
Swashbuckle 1.0 - 5.5 https://www.nuget.org/packages/Swashbuckle.Examples/
Swashbuckle.AspNetCore version 1.0.0 - 2.5.0 https://www.nuget.org/packages/Swashbuckle.AspNetCore.Examples/
Swashbuckle.AspNetCore version 3.0.0 https://www.nuget.org/packages/Swashbuckle.AspNetCore.Filters/
Swashbuckle.AspNetCore version 4.0.0 and above https://www.nuget.org/packages/Swashbuckle.AspNetCore.Filters/ Version >= 4.5.1
Swashbuckle.AspNetCore version 5.0.0-beta and above https://www.nuget.org/packages/Swashbuckle.AspNetCore.Filters/ Version >= 5.0.0-beta

What's included

Request example

Populate swagger's paths.path.[http-verb].requestBody.content.[content-type].example with whatever object you like.

This is great for manually testing and demoing your API as it will prepopulate the request with some useful data, so that when you click the example request in order to populate the form, instead of getting an autogenerated request like this:

autogenerated request with crappy data

You’ll get your desired example, with useful valid data, like this:

custom request with awesome data

You can see the example output in the underlying swagger.json file, which you can get to by starting your solution and navigating to swagger/v1/swagger.json

swagger.json

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

Response example

Allows you to add custom data to the example response shown in Swagger. So instead of seeing the default boring data like so:

response with crappy data

You'll see some more realistic data (or whatever you want):

response with awesome data

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

Security requirements filter

Adds security information to each operation so that you can send an Authorization header to your API. Useful for API endpoints that have JWT token authentication. e.g.

authorization button

bearer token

Add a request header

Adds any string to your request headers for all requests. I use this for adding a correlationId to all requests. request header

Add a response header

Allows you to specify response headers for any operation response headers

Add Authorization to Summary

If you use the [Authorize] attribute to your controller or to any actions, then (Auth) is added to the action's summary, along with any specified policies or roles.

authorization

Installation

  1. Install the NuGet package

  2. In the ConfigureServices method of Startup.cs, inside your AddSwaggerGen call, enable whichever filters you need

// 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<ExamplesOperationFilter>(); 
        // version 3.0 like this: c.AddSwaggerExamples(services.BuildServiceProvider());
        // version > 4.0 like this:
        c.ExampleFilters();
        
        c.OperationFilter<AddHeaderOperationFilter>("correlationId", "Correlation Id for the request", false); // adds any string you like to the request headers - in this case, a correlation id
        c.OperationFilter<AddResponseHeadersFilter>(); // [SwaggerResponseHeader]

        var filePath = Path.Combine(AppContext.BaseDirectory, "WebApi.xml");
        c.IncludeXmlComments(filePath); // standard Swashbuckle functionality, this needs to be before c.OperationFilter<AppendAuthorizeToSummaryOperationFilter>()

        c.OperationFilter<AppendAuthorizeToSummaryOperationFilter>(); // Adds "(Auth)" to the summary so that you can see which endpoints have Authorization
        // or use the generic method, e.g. c.OperationFilter<AppendAuthorizeToSummaryOperationFilter<MyCustomAttribute>>();

        // add Security information to each operation for OAuth2
        c.OperationFilter<SecurityRequirementsOperationFilter>();
        // or use the generic method, e.g. c.OperationFilter<SecurityRequirementsOperationFilter<MyCustomAttribute>>();

        // 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
        });
    });
}
  1. If you want to use the Request and Response example filters (and have called c.ExampleFilters() above), then you MUST also call
    services.AddSwaggerExamplesFromAssemblyOf<MyExample>();

or

    services.AddSwaggerExamplesFromAssemblyOf(typeof(MyExample));

or

    services.AddSwaggerExamplesFromAssemblies(Assembly.GetEntryAssembly());

This will register your examples with the ServiceProvider.

Serialize Swagger in the 2.0 format

There are two ways to tell Swashbuckle.AspNetCore to output the swagger.json in the legacy Swagger 2.0 format:

app.UseSwagger(c => c.SerializeAsV2 = true);

// OR

services.Configure<SwaggerOptions>(c => c.SerializeAsV2 = true);

If you want to SerializeAsV2 and you're using my Request example filter then you must call services.Configure<SwaggerOptions>(c => c.SerializeAsV2 = true);.

How to use

How to use - Request examples

DO NOT USE THIS FILTER UNLESS YOU HAVE TO

Since May 2018, Swashbuckle.AspNetCore supports adding examples via XML comments:

public class Product
{
    /// <summary>
    /// The name of the product
    /// </summary>
    /// <example>Men's basketball shoes</example>
    public string Name { get; set; }

This works for request examples and response examples, and it even works for example querystring and route parameters, i.e. on GET requests!

Example in a querystring on GET:

example on querystring

Example request body in a POST:

example request body

Example response:

example response

And soon (April 2020, once my Swashbuckle.AspNetCore PR has been released) you'll be able to add examples for primitive types on the querystring too, e.g.

/// <param name="id" example="123">The product id</param>
[HttpGet("{id}")]
public Product GetById(int id)

See the instructions on Swashbuckle.AspNetCore's Readme.

Therefore, I recommend that you move away from using my ExamplesOperationFilter. Personally, I don't use it any more and would like to deprecate it.

However, you may have a use case where XML comments doesn't work for you, e.g.

  • You want to generate examples at runtime not design time
  • You need XML request examples (not JSON)
  • You want examples to be added to the schema under the path, rather than the schema under the component
  • Some other ReDoc issue which I don't understand as I don't use ReDoc...

In which case, read on...

Automatic annotation

Version 4.0 and above supports automatic annotation.

Let's say you have a controller action which takes some input from the body, in this case a DeliveryOptionsSearchModel:

[HttpPost]
public async Task<IHttpActionResult> DeliveryOptionsForAddress([FromBody]DeliveryOptionsSearchModel search)

Then all you need to do is implement IExamplesProvider<DeliveryOptionsSearchModel>:

public class DeliveryOptionsSearchModelExample : IExamplesProvider<DeliveryOptionsSearchModel>
{
    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"
            }
        };
    }

And that's it.

Manual annotation

Alternatively, if you want to be more explicit, you can use the SwaggerRequestExample attribute. This is how it was done in versions 1.0 - 3.0. Any manual annotations will override automatic annotations.

Decorate your controller methods with the included SwaggerRequestExample attribute:

[HttpPost]
[SwaggerRequestExample(typeof(DeliveryOptionsSearchModel), typeof(DeliveryOptionsSearchModelExample))]
public async Task<IHttpActionResult> DeliveryOptionsForAddress([FromBody]DeliveryOptionsSearchModel search)

Now implement a IExamplesProvider<T>, in this case via a DeliveryOptionsSearchModelExample which will generate the example data. It should return the type you specified when you specified the [SwaggerRequestExample].

public class DeliveryOptionsSearchModelExample : IExamplesProvider<DeliveryOptionsSearchModel>
{
    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" }
                }
            }
        };
    }

In the Swagger document, this will populate the operation's requestBody content type example property. https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#mediaTypeObject

Here's what the OpenApi 3.0 spec says about it:

Field Name Type Description
example Any Example of the media type. The example object SHOULD be in the correct format as specified by the media type. The example object is mutually exclusive of the examples object. Furthermore, if referencing a schema which contains an example, the example value SHALL override the example provided by the schema.

List Request examples

As of version 2.4, List<T> request examples are supported. For any List<T> in the request, you may define a SwaggerRequestExample for T. Your IExamplesProvider should only return a single T and not a List<T>. Working example:

[SwaggerRequestExample(typeof(PeopleRequest), typeof(ListPeopleRequestExample))]
public IEnumerable<PersonResponse> GetPersonList([FromBody]List<PeopleRequest> peopleRequest)
{

// and then:

public class ListPeopleRequestExample : IExamplesProvider<PeopleRequest>
{
    public PeopleRequest GetExamples()
    {
        return new PeopleRequest { Title = Title.Mr, Age = 24, FirstName = "Dave in a list", Income = null };
    }
}

How to use - Response examples

AGAIN, DO NOT USE THIS FILTER UNLESS YOU HAVE TO

I repeat my earlier assertion - Since May 2018, Swashbuckle.AspNetCore supports adding examples via XML comments.

See above for instructions

If you still want to use it, read on...

Automatic annotation

Version 4.0 supports automatic annotation. If it's obvious which type your action returns, then no ProducesResponseType or SwaggerResponse attributes need to be specified, e.g.

public async Task<ActionResult<IEnumerable<Country>>> Get(string lang)
// or public ActionResult<IEnumerable<Country>> Get(string lang)
// or public IEnumerable<Country> Get(string lang)

Manual annotation

Alternatively, if you want to be more explicit, you can use the SwaggerResponseExample attribute. This is how it was done in versions 1.0 - 3.0. Any manual annotations will override automatic annotations.

Decorate your methods with the new SwaggerResponseExample attribute:

[SwaggerResponse(200, "The list of countries", typeof(IEnumerable<Country>))]
// or, like this [ProducesResponseType(typeof(IEnumerable<Country>), 200)]
[SwaggerResponseExample(200, typeof(CountryExamples))]
[SwaggerResponse(400, type: typeof(IEnumerable<ErrorResource>))]
public async Task<HttpResponseMessage> Get(string lang)

For manual annotation implement IExamplesProvider<T> to generate the example data

public class CountryExamples : IExamplesProvider<List<Country>>
{
    public List<Country> GetExamples()
    {
        return new List<Country>
        {
            new Country { Code = "AA", Name = "Test Country" },
            new Country { Code = "BB", Name = "And another" }
        };
    }
}

In the Swagger document, this will populate the operation's responses content example object. The spec for this says:

Field Pattern Type Description
example Any Example of the media type. The example object SHOULD be in the correct format as specified by the media type. The example object is mutually exclusive of the examples object. Furthermore, if referencing a schema which contains an example, the example value SHALL override the example provided by the schema.

Example response for application/json mimetype of a Pet data type:

 "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}"
              },

Known issues

  • Request examples are not shown for querystring parameters (i.e. HTTP GET requests, or for querystring parameters for POST, PUT etc methods). Request examples will only be shown in request body. This is as per the OpenApi 3.0 spec.

How to use - Multiple examples

Sometimes more than a single example are desirable for an API. In this case you can use IMultipleExamplesProvider<T> rather than IExamplesProvider<T> to return multiple examples. The example provider class is still located in the same way (automatic or manual annotation), but the GetExamples() call returns an enumerated list of examples along with their name and optional summary. To reduce boilerplate, it is recommended to use yield return for each example value. Every returned SwaggerExample<T> should have different value of Name property.

public class DeliveryOptionsSearchModelExample : IMultipleExamplesProvider<DeliveryOptionsSearchModel>
{
    public IEnumerable<SwaggerExample<DeliveryOptionsSearchModel>> GetExamples()
    {
        // An example without a summary.
        yield return SwaggerExample.Create(
            "Great Britain",
            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"
                }
            },
        );
    }

Note that UIs may choose to display the summary in different ways; in ReDoc, for example, the summary (if present) replaces the name in the UI.

How to use - Security requirements filter

First you need to already have OAuth2 configured correctly, and some of your controllers and actions locked down with the [Authorize] attribute. N.B. globally registered Authorization filters are not detected.

Then you need to tell Swagger that you're using OAuth2, as shown in the Installation section above:

    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
        });

This adds a securityDefinition to the bottom of the Swagger document, which Swagger-UI renders as an "Authorize" button, which when clicked brings up the Authorize dialog box shown above.

Then, when you enable the SecurityRequirementsOperationFilter:

	// add Security information to each operation for OAuth2
	c.OperationFilter<SecurityRequirementsOperationFilter>();

It adds a security property to each operation, which renders in Swagger-UI as a padlock next to the operation: locked down actions

By default, the SecurityRequirementsOperationFilter also adds 401 and 403 to each operation that has [Authorize] on it: 401 and 403

If you don't want to do that you can pass false when you configure it:

	c.OperationFilter<SecurityRequirementsOperationFilter>(false);

How to use - Request Header

When you enable the filter in your Startup.cs, as per the Installation section above, you can specify the name (string) and description (string) of the new header parameter, as well as whether it is required or not (bool). This will add the input box to every controller action.

How to use - Response headers

Specify one or more [SwaggerResponseHeader] attributes on your controller action. You can specify the status code (int), header name (string), type (string), description (string) and format (string). See the OpenAPI Specification spec for information on DataTypes: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#dataTypes

[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)
{

How to use - Authorization summary

Specify [Authorization] headers on either a Controller:

[Authorize]
public class ValuesController : Controller

or on an action:

[Authorize("Customer")]
public PersonResponse GetPerson([FromBody]PersonRequest personRequest)

You can optionally specify policies [Authorize("Customer")] or roles [Authorize(Roles = "Customer")] and they will be added to the Summary too.

Pascal case or Camel case?

The default is camelCase. If you want PascalCase you can pass in a DefaultContractResolver like so: [SwaggerResponseExample(200, typeof(PersonResponseExample), typeof(DefaultContractResolver))]

The above is no longer supported - it will output Examples using whichever JSON serializer your controllers are configured with in services.AddControllers().

Render Enums as strings

By default enums will output their integer values. If you want to output strings you can pass in a StringEnumConverter like so: [SwaggerResponseExample(200, typeof(PersonResponseExample), jsonConverter: typeof(StringEnumConverter))]

The above is no longer supported - it will output Examples using whichever JSON serializer your controllers are configured with in services.AddControllers().

Advanced: Examples with Dependency injection

If for some reason you need to have examples with DI (for example, to read them from a database), you can use constructor injection:

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 };
    }
}

Then, you should register the Swagger examples via the extension methods:

services.AddSwaggerExamplesFromAssemblyOf<PersonRequestExample>();

or

services.AddSwaggerExamplesFromAssemblyOf(typeof(PersonRequestExample));

or

services.AddSwaggerExamplesFromAssemblies(Assembly.GetEntryAssembly());

If you are using services.AddSwaggerExamples(), then you would have to manually register your IExamplesProvider class:

services.AddSingleton<PersonRequestExample>();

The FromAssemblyOf<T> extension method is the recommended approach.

About

A bunch of useful filters for Swashbuckle.AspNetCore

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • C# 100.0%