ASP.NET Core 在 Swagger UI 中显示自定义的 Header或者在url中增加query参数

会遇到有些api接口中,会在实际调用过程中在url加参数,或者加Header。在Swagger中该如何实现
 using Swashbuckle.AspNetCore.Swagger;
 using Swashbuckle.AspNetCore.SwaggerGen;    
    /// 控制swagger中是否需要添加accesstoken验证
    /// 
    public class AddAuthTokenHeaderParameter : IOperationFilter
    {
        /// 
        /// 
        /// 
        /// 
        /// 
        public void Apply(Operation operation, OperationFilterContext context)
        {
            if (operation.Parameters == null) operation.Parameters = new List();
            var attrs = context.ApiDescription.ActionDescriptor.AttributeRouteInfo;

            //先判断是否是匿名访问,
            var descriptor = context.ApiDescription.ActionDescriptor as ControllerActionDescriptor;
            if (descriptor != null)
            {
                var actionAttributes = descriptor.MethodInfo.GetCustomAttributes(inherit: true);
                bool isAnonymous = actionAttributes.Any(a => a is AllowAnonymousAttribute);
                 //非匿名的方法,链接中添加accesstoken值
                if (!isAnonymous)
                {
                    operation.Parameters.Add(new NonBodyParameter()
                    {
                        Name = "accesstoken",
                        In = "query",//query header body path formData
                        Type = "string",
                        Required = true //是否必选
                    });
                }
            }
        }
    }
其中NonBodyParameter类中的In属性可以为query,header,body,path,formData. 分别为在url查询参数、header、body、url路径、表单数据中添加项。 这里可参考官网解释

然后在StartUp的ConfigureServices方法中绑定
 public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(options => { options.Filters.Add(); });
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new Info
                {
                    Version = "v1",
                    Title = "Test API"
                });
                //swagger中控制请求的时候发是否需要在url中增加accesstoken
                options.OperationFilter();

                //Determine base path for the application.  
                var basePath = PlatformServices.Default.Application.ApplicationBasePath;
                //Set the comments path for the swagger json and ui.  
                var xmlPath = Path.Combine(basePath, "TestDemo.xml");
                options.IncludeXmlComments(xmlPath);
            });
        }

最终Swagger界面如下:

ASP.NET Core 在 Swagger UI 中显示自定义的 Header或者在url中增加query参数_第1张图片




你可能感兴趣的:(NetCore)