Swagger配置

Authorization给所有接口都加上一个认证授权机制
C#
//配置Swagger
builder.Services.AddSwaggerGen(options =>
{
    // 设置标题和版本
    options.SwaggerDoc("v1", new OpenApiInfo { Title = "ICHIAPI", Version = "v1" });
    // 设置对象类型参数默认值
    options.SchemaFilter<DefaultValueSchemaFilter>();
    //添加安全定义
    options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
    {
        Description = "请输入token,格式为 Bearer xxxxxxxx(注意中间必须有空格)",
        Name = "Authorization",
        In = ParameterLocation.Header,
        Type = SecuritySchemeType.ApiKey,
        BearerFormat = "JWT",
        Scheme = "Bearer"
    });
    //添加安全要求
    options.AddSecurityRequirement(new OpenApiSecurityRequirement {
                    {
                        new OpenApiSecurityScheme{
                            Reference =new OpenApiReference{
                                Type = ReferenceType.SecurityScheme,
                                Id ="Bearer"
                            }
                        },Array.Empty<string>()
                    }
     });
});
SchemaFilter配置
C#
public class DefaultValueSchemaFilter : ISchemaFilter
{
    public void Apply(OpenApiSchema schema, SchemaFilterContext context)
    {
        if (schema == null)
        {
            return;
        }
        var objectSchema = schema;
        foreach (var property in objectSchema.Properties)
        {
            // 按照数据的类型去指定默认值
            if (property.Value.Type == "string" && property.Value.Default == null)
            {
                property.Value.Default = new OpenApiString("");
            }
            // 按照字段名去指定默认值
            else if (property.Key == "pageIndex")
            {
                property.Value.Example = new OpenApiInteger(1);
            }
            else if (property.Key == "pageSize")
            {
                property.Value.Example = new OpenApiInteger(10);
            }
            // 通过特性来实现
            DefaultValueAttribute defaultAttribute = context.ParameterInfo?.GetCustomAttribute<DefaultValueAttribute>();
            if (defaultAttribute != null)
            {
                property.Value.Example = (IOpenApiAny)defaultAttribute.Value;
            }
        }
    }
}
订阅评论
提醒
0 评论
最旧
最新 最多投票
内联反馈
查看所有评论
滚动至顶部