Article directory
only one version
The first step is to add annotations on the controller and each interface method as shown in the figure
Step 2: Open the .csproj file of the project and add
<GenerateDocumentationFile>true</GenerateDocumentationFile>
Step 3: Add the following code in the Program.cs configuration file:
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);
});
The effect is as follows
multiple versions
Step 1: Customize a class first: The author is: ApiVersionInfo.cs The code is as follows:
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;
}
}
Step 2: Specify which version the control belongs to. Add code to the controller:
[ApiExplorerSettings(GroupName =nameof(ApiVersionInfo.接口版本V1))]
Step 3: Add the following code in the Program.cs configuration file:
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}");
}
});
}
Effect:
Reprinted from: https://blog.csdn.net/q8812345qaz/article/details/127808452