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

会遇到有些api接口中,会在实际调用过程中在url加参数,或者加Header。在Swagger中该如何实现
 using Swashbuckle.AspNetCore.Swagger;
 using Swashbuckle.AspNetCore.SwaggerGen;    
    /// 控制swagger中是否需要添加accesstoken验证
    /// </summary>
    public class AddAuthTokenHeaderParameter : IOperationFilter
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="operation"></param>
        /// <param name="context"></param>
        public void Apply(Operation operation, OperationFilterContext context)
        {
            if (operation.Parameters == null) operation.Parameters = new List<IParameter>();
            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<AuthActionFilter>(); });
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new Info
                {
                    Version = "v1",
                    Title = "Test API"
                });
                //swagger中控制请求的时候发是否需要在url中增加accesstoken
                options.OperationFilter<AddAuthTokenHeaderParameter>();

                //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界面如下:

相关文章
相关标签/搜索