Keywords: Swagger | Web API | Header Parameter | IOperationFilter | C#
Abstract: This article explains how to automatically add header parameters, such as authorization tokens, to all API methods in Swagger using the IOperationFilter interface in ASP.NET Web API. Based on the best answer, it details implementation steps, code examples, adaptations for Swagger 5, and alternative approaches to enhance API documentation consistency.
Introduction
In modern web API development, Swagger is widely used for API documentation. A common requirement is to automatically add header parameters, such as authorization tokens, to every API method in Swagger UI. This can be achieved by implementing the IOperationFilter interface provided by Swashbuckle.AspNetCore.SwaggerGen.
Core Solution: Using IOperationFilter
The most effective approach is to implement the IOperationFilter interface. Based on the best answer, here are the steps:
- Create a custom class that implements the
IOperationFilterinterface. - In the
Applymethod, add the header parameter to the operation parameters. - Register the filter in the Swagger configuration.
Example code:
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
public class AddRequiredHeaderParameter : IOperationFilter
{
public void Apply(Operation operation, OperationFilterContext context)
{
if (operation.Parameters == null)
operation.Parameters = new List<IParameter>();
operation.Parameters.Add(new NonBodyParameter
{
Name = "X-User-Token",
In = "header",
Type = "string",
Required = false
});
}
}Then, in your Swagger configuration (e.g., in Startup.cs or Program.cs), add:
c.OperationFilter<AddRequiredHeaderParameter>();Adapting to Swagger 5
For Swagger 5 and above, the models have been updated. Refer to other answers for changes, such as using OpenApiOperation instead of Operation, OpenApiParameter instead of IParameter, and updating Schema settings.
Alternative Method: Adding Parameters at Controller Level
Another approach is to add header parameters directly in controller actions using attributes like [FromHeader]. For example:
[HttpPost]
public IActionResult Test([FromHeader(Name="x-test")][Required] string requiredHeader)
{
return Ok();
}Conclusion
Using IOperationFilter is the recommended way to add global header parameters in Swagger, as it centralizes configuration and ensures consistency across all APIs. Developers can choose the appropriate version or method based on project requirements.