vs2022 搭建NET6 WebApi 接口项目《二》 配置swagger

1、在Program.cs中配置以下代码

     

#region 添加swagger注释
var basePath = AppContext.BaseDirectory;
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo
    {
        Version = "v1",
        Title = "Api"
    });
    var xmlPath = Path.Combine(basePath, "TestApi.xml");// 注意这里接口的xml名称,与项目名保持一致
    c.IncludeXmlComments(xmlPath, true);
    var xmlDomainPath = Path.Combine(basePath, "TestDomain.xml"); // 注意这里实体类的xml名称,与项目名保持一致
    c.IncludeXmlComments(xmlDomainPath, true);
    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
    {
        Description = "Value: Bearer {token}",
        Name = "Authorization",
        In = ParameterLocation.Header,
        Type = SecuritySchemeType.ApiKey,
        Scheme = "Bearer"
    });
    c.AddSecurityRequirement(new OpenApiSecurityRequirement()
    {
      {
        new OpenApiSecurityScheme
        {
          Reference = new OpenApiReference
          {
            Type = ReferenceType.SecurityScheme,
            Id = "Bearer"
          },Scheme = "oauth2",Name = "Bearer",In = ParameterLocation.Header,
        },new List<string>()
      }
    });
});
#endregion

2、启用swagger,配置以下代码

     

#region 启用swaggerUI
app.UseSwagger();
app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "V1 Docs");
    c.RoutePrefix = string.Empty;
    c.DocExpansion(Swashbuckle.AspNetCore.SwaggerUI.DocExpansion.None);
    c.DefaultModelsExpandDepth(-1);
});
#endregion

3、配置实体类文档和接口文档

     1、配置接口文档,选中TestApi项目右键属性,在生成->输出中勾选 “生成包含API文档的文件”

          

 

 

      2、配置实体类文档,选中TestDomain项目右键属性,在生成->输出中勾选 “生成包含API文档的文件”

     

 

 

 4、项目直接跑起来,可能路径是最后的后缀是swagger,导致直接shit了,所以这里需要去删除启动路径,找到launchSettings.json文件,删除  "launchUrl": "swagger" 这个,打开的路径就是https://localhost:7030/index.html   

        

 

 

       最终的效果就是这样的

      

 

posted @ 2022-04-08 23:31  程序原快递  阅读(3062)  评论(0编辑  收藏  举报