0

I know that I can add header parameter for all API in swagger as described in Web Api How to add a Header parameter for all API in Swagger

With this approach, the header parameter will show up in swagger UI for all APIs.

But not all of my APIs/controllers need the header parameter, is there a way to add header only for specific controller or even a specific API?

Youxu
  • 1,050
  • 1
  • 9
  • 34

2 Answers2

2

Though this post is old, I thought it would help new comers if they get stuck in the same situation.

public class AddRequiredHeaderParameter : IOperationFilter
{
    public void Apply(Operation operation, SchemaRegistry schemaRegistry,
                      ApiDescription apiDescription)
    {
        if (operation.parameters == null)
        {
            operation.parameters = new List<Parameter>();
        }

       /*System.Diagnostics.Trace.WriteLine(apiDescription.RelativePath +
          "=paath");*/
        if (apiDescription.RelativePath.Contains(***{url***}))
        {
            operation.parameters.Add(new Parameter
            {
                name = "X-User-Token",
                @in = "header",
                type = "string",
                required = false,
                description=""
            });
            operation.parameters.Add(new Parameter
            {
                name = "authorization",
                @in = "header",
                description = "Token",
                type = "string",
                required = true
            });
        }
        else
        {
            operation.parameters.Add(new Parameter
            {
                name = "X-User-Token",
                @in = "header",
                type = "string",
                required = false,
                description="description"
            });
        }
    }
}
0

In Asp.Net Core/.net6


using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Swashbuckle.AspNetCore.SwaggerGen;
using Microsoft.OpenApi.Models;


namespace YourProduct
{
    public class HttpHeaderOperationFilter : IOperationFilter
    {
        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {
            
            operation.Parameters.Add(new OpenApiParameter
            {
                Name = "X-your-Custom-header",
                In = ParameterLocation.Header,
                AllowEmptyValue = true,
                Required = false,
                Description = "Your custom header Name"
                
            });
        }
    }
}

in the action

[HttpPost("[action]")]
[SwaggerOperationFilter(typeof(HttpHeaderOperationFilter))] //<-- point of interest
public IActionResult DoSomething([FromBody] YourModel model)
{
. . . . . . .

And don't forget startup.cs

services.AddSwaggerGen(opt =>
{
    opt.EnableAnnotations(); // <-- this
}
T.S.
  • 18,195
  • 11
  • 58
  • 78