Question: Web Api How to add a Header parameter for all API in Swagger

Question

Web Api How to add a Header parameter for all API in Swagger

Answers 1
Added at 2017-01-05 20:01
Tags
Question

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 to do something about it.

Answers
nr: #1 dodano: 2017-01-05 20:01

Yes you can do it via inheriting from IOperationFilter

You can find the answer on github here: AddRequiredHeaderParameter

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

        operation.parameters.Add(new Parameter
        {
            name = "X-User-Token",
            @in = "header",
            type = "string",
            required = false
        });
    }
}

Then you go to your SwaggerConfig.cs file and add the following in the EnableSwagger section:

   c.OperationFilter(() => new AddRequiredHeaderParameter());

Rebuild, and enjoy.

Source Show
◀ Wstecz