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.
How to set a default value for each parameter?
Thank you
As of writing this having the OpenApiSchema Type as “String” breaks the Swagger UI. If you switch to “string” it will work just fine. This is just for anyone who might run into the same issue I did.
Thanks for the article!
Thank you, Steve. Glad to have your comments!
Hi,
From my experience there’s a difference between using the FromHeaderAttribute and the creating an IOperationFilter. Using the FromHeaderAttribute the framework will verify the header is present before allowing a request to be processed. I don’t see this being the case when using an IOperationFilter.
Is there a means to tap into the FromHeaderAttribute in order to configure required headers dynamically? I have a requirement where I need to be able to specify a number of headers to be present and also have it noted in the OpenAPI spec.
Hi Tim- Sorry for the delay in reply. If you want to tap any header before your actual API/Controller pipelines, you can try it using the middleware approach. Any header specified in the middleware will be available for OpenSpec through the HttpContext. Please visit for your reference – https://thecodebuzz.com/add-custom-headers-to-response-in-asp-net-core/
Hope this helps you!
Hi – Thanks. what is best practices to name custom header ? Should we use with x as as start letter ?
Thanks Mark for your query. I do see good guidelines here in this post,
https://specs.openstack.org/openstack/api-wg/guidelines/headers.html#guidance
Hope this helps.
Thanks