隐藏 header 以防在 Swagger Swashbuckle 中显示

Hide a header from being displayed in Swagger Swashbuckle

因为我已经添加了一个公共授权,我如何从每个 API 中删除单独的(授权 header),如下图 link 所示?

swaggerHub_Link

我想通了:

您可以简单地创建一个自定义属性和一个继承自 Swashbuckle.AspNetCore.SwaggerGen.IOperationFilter 的操作过滤器,以隐藏 header 不显示在 swagger.json

public class OpenApiHeaderIgnoreAttribute : System.Attribute
{
}

class 名称应以基地名称结尾 class。

public class OpenApiHeaderIgnoreFilter : Swashbuckle.AspNetCore.SwaggerGen.IOperationFilter
{
    public void Apply(Microsoft.OpenApi.Models.OpenApiOperation operation, Swashbuckle.AspNetCore.SwaggerGen.OperationFilterContext context)
    {
        if (operation == null || context == null || context.ApiDescription?.ParameterDescriptions == null)
            return;

        var parametersToHide = context.ApiDescription.ParameterDescriptions
            .Where(parameterDescription => ParameterHasIgnoreAttribute(parameterDescription))
            .ToList();

        if (parametersToHide.Count == 0)
            return;

        foreach (var parameterToHide in parametersToHide)
        {
            var parameter = operation.Parameters.FirstOrDefault(parameter => string.Equals(parameter.Name, parameterToHide.Name, System.StringComparison.Ordinal));
            if (parameter != null)
                operation.Parameters.Remove(parameter);
        }
    }

    private static bool ParameterHasIgnoreAttribute(Microsoft.AspNetCore.Mvc.ApiExplorer.ApiParameterDescription parameterDescription)
    {
        if (parameterDescription.ModelMetadata is Microsoft.AspNetCore.Mvc.ModelBinding.Metadata.DefaultModelMetadata metadata)
        {
            return metadata.Attributes.ParameterAttributes.Any(attribute => attribute.GetType() == typeof(OpenApiParameterIgnoreAttribute));
        }

        return false;
    }
}

并在您的启动 class configureServices 方法中设置此过滤器 class,如下所示:

public void ConfigureServices(IServiceCollection services)
{
    services.AddSwaggerGen(c =>
    {
        c.OperationFilter<OpenApiHeaderIgnoreFilter>();
    }
}

并更新控制器中的 API 方法,如下所示:

[EnableQuery]
[SwaggerOperation(Tags = new[] { "Odata" })]
public async Task<IActionResult> Get([OpenApiHeaderIgnore] [FromHeader(Name = ClaimNames.AccessToken)] string token)
{
// code
}