Adding Default Headers to Swagger (OpenAPI)

Posted by

Recently, we had a requirement to pass a mandatory/ default header to all our HTTP POST requests. Our application is built on ASP.NET Core 3.1 and uses Swagger to describe and expose our Web APIs to the consumer.

To ensure that each POST request includes the required header, I intended to add the header information to the Swagger (now OpenAPI) Definition. Here’s how I was able to achieve this.

To use Swagger/ Open API in your .NET Core 3+ application, you need to use Swashbuckle.AspNetCore version 5.0 in your project. At the time of writing, this NuGet package is still in preview.

dotnet add package Swashbuckle.AspNetCore

A typical ASP.NET Core 3.1 Startup project with a Swagger definition looks as below:

To add the default header to each POST request, implement IOperationFilter as below:

Now, Update AddSwaggerGenCommand in Startup → ConfigureServices method to include the new DefaultHeaderFilter

That’s it! Your Swagger UI will now have the default header for each POST request with this change.

Swagger with Default Header
Advertisements