如何使用c#在swagger中添加Authorization标头

时间:2017-10-25 05:37:49

标签: swagger swagger-editor

我在visual studio 2015 web应用程序中安装了swagger并且工作正常。但是该部分缺少授权部分如何在c#mvc web应用程序Swagger中添加授权头。 提前致谢。 http://prntscr.com/h1ohww

1 个答案:

答案 0 :(得分:0)

1,编写一个过滤器

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

        operation.parameters.Add(new Swashbuckle.Swagger.Parameter
        {
            name = "Authorization",                
            type = "string",
            @in = "header",
            required = false // set to false if this is optional
        });
    }
}

2,在Startup.cs的Swagger配置中启用此过滤器

config.EnableSwagger(c =>
         {
             c.SingleApiVersion("v1", "SwaggerUi");
             c.IncludeXmlComments(string.Format(@"{0}\bin\{1}.XML", AppDomain.CurrentDomain.BaseDirectory, typeof(SwaggerConfig).Assembly.GetName().Name));
             c.IncludeXmlComments(string.Format(@"{0}\bin\{1}.XML", AppDomain.CurrentDomain.BaseDirectory, "Elephant.Entity"));
             c.OperationFilter<MyHeaderFilter>();
         })
         .EnableSwaggerUi(c =>
         {
         });

祝你好运!