Add a Custom header parameter to .NET Core API in Swagger –OpenAPI

In this article, we will learn how to add a custom header parameter to .NET Core API in Swagger (OpenAPI) documentation.
Today in this article, we will cover below aspects,
Custom headers are helpful when you want to add metadata to your API requests or responses or when you need specific headers for authentication, security, or other purposes.
Documenting custom headers in Swagger ensures that developers consuming your API understand the header requirements and can use the API effectively.
In Swagger/OpenAPI, you can document and define custom headers to be used in your API requests and responses.
Step1 – Create ASP.NET Core API
Create .NET API application
Step2: Install the required NuGet package
Using CLI tool
dotnet add package Swashbuckle.AspNetCore
OR
Using PMC(package manager console)
PM> Install-Package Swashbuckle.AspNetCore -Version <version>
Approach1 – Using IOperationFilter to add a header to swagger
Create a custom class with the name of your choice ‘CustomHeaderSwaggerAttribute‘ derived from ‘IOperationFilter‘ and overriding Apply method as below,
public class CustomHeaderSwaggerAttribute : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
if (operation.Parameters == null)
operation.Parameters = new List<OpenApiParameter>();
operation.Parameters.Add(new OpenApiParameter
{
Name = "X-CustomHeader",
In = ParameterLocation.Header,
Required = true,
Schema = new OpenApiSchema
{
Type = "string"
}
});
}
}
The above logic will be applied globally to all APIs. You can control the same based on each API if required using attribute filter techniques.
Let’s enable this custom Operation filter in the ConfigureServices method as below,
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title ="MyTestService", Version = "v1", });
c.OperationFilter<CustomHeaderSwaggerAttribute>();
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath);
});
}
Please see the swagger OpenAPI documentation below,

Approach2 – Using FromHeaderAttribute to add a header to swagger
One can also use a declarative approach by using FromHeaderAttribute using FromHeader,
[HttpPost]
public IActionResult Weather([FromHeader(Name = "x-CustomHeader2")] string city)
{
return Ok();
}
Let’s view generated swagger,

Do you have any comments or ideas or any better suggestions to share?
Please sound off your comments below.
Happy Coding !!
References:
Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.