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:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
To add the default header to each POST request, implement IOperationFilter as below:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Now, Update AddSwaggerGenCommand in Startup → ConfigureServices method to include the new DefaultHeaderFilter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Leave a Reply