.NET10 中配置Swagger的记录

项目的.csproj配置

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.5" />  
    <PackageReference Include="Swashbuckle.AspNetCore" Version="10.1.5" />
  </ItemGroup>

项目属性配置

项目属性中
生成->输出->文档文件 勾选生成包含API文档的文件

创建一个多版本管理类

我放在了Utility/ApiVersions.cs  注意这里使用字段不是属性,和后面代码的调用对应,如果使用属性需要同步修改后面Program.cs中的代码

    public class ApiVersions
    {
        public string V1;
        public string V2;
        public string V3;
    }

Program.cs中的代码配置

 1 #region 配置Swagger服务
 2 {
 3     builder.Services.AddEndpointsApiExplorer();
 4     builder.Services.AddSwaggerGen(options =>
 5     {
 6         #region 支持注释
 7         string basePath = Path.GetDirectoryName(AppContext.BaseDirectory);
 8         string xmlPath = Path.Combine(basePath, $"{System.Reflection.Assembly.GetExecutingAssembly().GetName().Name}.xml");
 9         options.IncludeXmlComments(xmlPath);
10         #endregion
11 
12         #region 支持多版本
13         foreach(FieldInfo field in typeof(ApiVersions).GetFields())
14         {
15             string version = field.Name;
16             options.SwaggerDoc(version, new OpenApiInfo
17             {
18                 Version = version,
19                 Title = $"One API {version}",
20                 Description = $"One API接口文档 {version}"
21             });
22         }
23         #endregion
24     });
25 }
26 #endregion
27 var app = builder.Build();
28 
29 // Configure the HTTP request pipeline.
30 if (app.Environment.IsDevelopment())
31 {
32     app.MapOpenApi();
33 }
34 #region 配置Swagger中间件
35 {
36     app.UseSwagger();
37     app.UseSwaggerUI(options =>
38     {
39         foreach (FieldInfo field in typeof(ApiVersions).GetFields())
40         {
41             string version = field.Name;
42             options.SwaggerEndpoint($"/swagger/{version}/swagger.json", $"One API {version}");
43         }
44         //options.RoutePrefix = string.Empty; // 设置Swagger UI的根路径
45     });
46 }
47 #endregion

这里重点是两部分配置,一部分配置Swagger服务,放在var app = builder.Build();前面,另一部分,Swagger中间件配置放var app = builder.Build();后面

posted @ 2026-03-24 09:55  uxinxin  阅读(2)  评论(0)    收藏  举报