只有一个版本
第一步 首先 在 控制器上 和 每个接口方法 上 添加 注释 如图
第二步 :打开项目的.csproj文件加上 添加
<GenerateDocumentationFile>true</GenerateDocumentationFile>
第三步: 在 Program.cs配置文件中添加 如下代码:
builder.Services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new OpenApiInfo
{
Version = "v1",
Title = "API标题",
Description = $"API描述,v1版本"
});
var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
//IncludeXmlComments 第二参数 true 则显示 控制器 注释
options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename), true);
});
效果如下
多个版本
第一步:先自定义一个类:笔者为:ApiVersionInfo.cs 代码如下:
namespace WebApplication2
{
/// <summary>
/// api版本号
/// </summary>
public class ApiVersionInfo
{
public static string 接口版本V1;
public static string 接口版本V2;
public static string 接口版本V3;
public static string 接口版本V4;
public static string 接口版本V5;
}
}
第二步:规定 控制属于 哪个 版本。在控制器上 添加代码:
[ApiExplorerSettings(GroupName =nameof(ApiVersionInfo.接口版本V1))]
第三步:在 Program.cs配置文件中添加 如下代码:
builder.Services.AddSwaggerGen(options =>
{
foreach (FieldInfo fileld in typeof(ApiVersionInfo).GetFields())
{
options.SwaggerDoc(fileld.Name, new OpenApiInfo
{
Version = fileld.Name,
Title = "API标题",
Description = $"API描述,{fileld.Name}版本"
});
}
var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
//IncludeXmlComments 第二参数 true 则显示 控制器 注释
options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename),true);
});
省略的代码。。。。。。。。。
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI(c =>
{
foreach (FieldInfo field in typeof(ApiVersionInfo).GetFields())
{
c.SwaggerEndpoint($"/swagger/{field.Name}/swagger.json", $"{field.Name}");
}
});
}
效果:
转载自:https://blog.csdn.net/q8812345qaz/article/details/127808452