How to add custom header in swagger operation

I am currently developing a .net core web API that will use a swagger as its documentation. 
Everything was perfect, except almost of the request method has a required data that was in the header. 
My problem was how to add an input header in the Swagger UI. After a few research, I found it. Here's how to do it.
  1. Create a filter class that implement IOperationFilter
    
    
      public class MyCustomHeaderFilter : IOperationFilter
        {
            public void Apply(OpenApiOperation operation, OperationFilterContext context)
            {
                if (operation.Parameters != null)
                {
                    operation.Parameters.Add(new OpenApiParameter
                    {
                        Name = "FilterName",
                        In = ParameterLocation.Header,
                        Description = "access token",
                        Required = false,
                    });
                }
    
            }
        }
    
    
  2. Register the class in swagger using OperationFilter
           
        swagger.OperationFilter<TenantCodeOperationHeader>();
        
        

Comments

Popular posts from this blog