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

后端 未结 7 1068
温柔的废话
温柔的废话 2020-11-27 16:54

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.

7条回答
  •  温柔的废话
    2020-11-27 17:03

    If swagger is used in ASP.Net MVC5, and required to add headers to get input from swagger UI.

    Create a class inherited from IOperationFilter:

    using Swashbuckle.Swagger;
    using System.Collections.Generic;
    using System.Web.Http.Description;
    
    public class AddHeaderParameters : IOperationFilter
    {
        public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            if (operation.parameters == null)
                operation.parameters = new List();
    
            operation.parameters.Add(new Parameter
            {
                name = "AccountUserName",
                @in = "header",
                type = "string",
                required = true,
                //description = "Account username"
            });    
        }
    }
    

    Give reference of this class in SwaggerConfig.cs inside Configuration.EnableSwagger as:

    c.OperationFilter();
    

    Important thing to note that the header name supposed to match with the actual header you have created for API.

提交回复
热议问题