#region 添加Swagger
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Title = "API Demo",
Version = "v1"
});
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath, true);
c.DocInclusionPredicate((string docName, ApiDescription description) => true);
c.CustomSchemaIds((Type x) => x.FullName);
c.ResolveConflictingActions((IEnumerable<ApiDescription> p) => p.First());
#region 自定义Token头
//Bearer 的scheme定义
var securityScheme = new OpenApiSecurityScheme()
{
Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
Name = "Authorization",
//参数添加在头部
In = ParameterLocation.Header,
//使用Authorize头部
Type = SecuritySchemeType.Http,
//内容为以 bearer开头
Scheme = "bearer",
BearerFormat = "JWT"
};
//把所有方法配置为增加bearer头部信息
var securityRequirement = new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "bearerAuth"
}
},
new string[] {}
}
};
//注册到swagger中
c.AddSecurityDefinition("bearerAuth", securityScheme);
c.AddSecurityRequirement(securityRequirement);
#endregion
});
#endregion
#region 使用Swagger
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "API Demo v1");
c.DefaultModelsExpandDepth(-1);
//c.ConfigObject.AdditionalItems.Add("syntaxHighlight", false);
//c.ConfigObject.AdditionalItems.Add("theme", "agate");
});
#endregion