Skip to content

Swashbuckle 如何在 Swagger UI 上添加 Header

🏷️ Swagger

  1. 创建一个 IOperationFilter 的实现

    csharp
    public class AuthTokenHeaderParameter : IOperationFilter
    {
        public void Apply(Operation operation, OperationFilterContext context)
        {
            operation.Parameters = operation.Parameters ?? new List<IParameter>();
            //MemberAuthorizeAttribute 自定义的身份验证特性标记
            var isAuthor = operation != null && context != null;
            if (isAuthor)
            {
                //in query header
                operation.Parameters.Add(new NonBodyParameter()
                {
                    Name = "Authenticate",
                    In = "header", //query formData ..
                    Description = "身份验证",
                    Required = false,
                    Type = "string"
                });
            }
        }
    }
  2. Startup.csConfigureServices 方法中做些修改

    csharp
    services.AddSwaggerGen(c =>
    {
        // ...
        c.OperationFilter<AuthTokenHeaderParameter >();
    });

原文:.NET Core API 框架实战(二)Swagger 中创建 Token 头工具并创建 Controller 描述过滤器 DocumentFilter