I searched for possible ways to add a request header parameter that would be added automatically to every method in my web-api
but I couldn't find a clear one.
While searching I found that the method OperationFilter()
has something to do with it.
Yes you can do it via inheriting from IOperationFilter
You can find the answer on GitHub here: AddRequiredHeaderParameter
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 you go to your SwaggerConfig.cs
file and add the following in the AddSwaggerGen
section:
c.OperationFilter<AddRequiredHeaderParameter>();
Rebuild, and enjoy.