Asp.Net Core swagger接口文档添加Header

 1、添加Filter类


    public class JwtHeaderFilter : IOperationFilter
    {
        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {
            var isAuthorized = context.MethodInfo.GetCustomAttributes(typeof(AuthorizeAttribute),false);
            if (isAuthorized == null || isAuthorized.Length == 0)
                isAuthorized = ((Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor)context.ApiDescription.ActionDescriptor).ControllerTypeInfo.GetCustomAttributes(typeof(AuthorizeAttribute), false);

            var allowAnonymous = context.MethodInfo.GetCustomAttributes(typeof(AllowAnonymousAttribute), false);
            if (allowAnonymous == null || allowAnonymous.Length == 0)
                allowAnonymous = ((Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor)context.ApiDescription.ActionDescriptor).ControllerTypeInfo.GetCustomAttributes(typeof(AllowAnonymousAttribute), false);

            if (isAuthorized != null && isAuthorized.Length >= 1 && (allowAnonymous == null || allowAnonymous.Length == 0))
            {
                if (operation.Parameters == null)
                    operation.Parameters = new List<OpenApiParameter>();

                operation.Parameters.Add(new OpenApiParameter
                {
                    Name = "Authorization",
                    In = ParameterLocation.Header,
                    Description = "Token",
                    Required = true,
                    Schema = new OpenApiSchema
                    {
                        Type = "string",
                        Default = new OpenApiString("Bearer ")
                    }
                });
            }
        }
    }

2、配置swagger

private static void ConfigureSwaggerServices(ServiceConfigurationContext context, IConfiguration configuration)
        {
            context.Services.AddAbpSwaggerGen( //非ABP VNext框架,改成AddSwaggerGen
                options =>
                {
                    options.SwaggerDoc("v1", new OpenApiInfo { Title = "Demo API", Version = "v1" });
                    options.DocInclusionPredicate((docName, description) => true);
                    options.CustomSchemaIds(type => type.FullName);
                    options.OperationFilter<JwtHeaderFilter>(); //这里使用Filter
                });
        }