什么是 Swagger?
Swagger 是一個(gè)規(guī)范和完整的框架,用于生成、描述、調(diào)用和可視化 RESTful 風(fēng)格的 Web 服務(wù)。它提供了一種規(guī)范的方式來定義、構(gòu)建和文檔化 RESTful Web 服務(wù),使客戶端能夠發(fā)現(xiàn)和理解各種服務(wù)的功能。Swagger 的目標(biāo)是使部署管理和使用功能強(qiáng)大的 API 從未如此簡單。
Swagger 提供了一種基于 YAML 或 JSON 格式的規(guī)范語言,用于描述 RESTful Web 服務(wù)的元數(shù)據(jù),包括 API 的版本、資源、請求方法、參數(shù)、響應(yīng)等信息。通過使用 Swagger 工具,開發(fā)人員可以生成 API 文檔,并與可視化工具集成,提供了一個(gè)用戶友好的界面來測試和使用 API。
此外,Swagger 還提供了一些額外的功能,如 API 的版本控制、認(rèn)證和授權(quán)、API 的監(jiān)控和度量等。這些功能可以幫助開發(fā)人員更好地管理和維護(hù) RESTful Web 服務(wù)。
總之,Swagger 是一個(gè)強(qiáng)大的工具,可以幫助開發(fā)人員構(gòu)建、文檔化和使用 RESTful Web 服務(wù),提高 API 的開發(fā)效率和管理水平。
什么是 Swashbuckle.AspNetCore?
Swashbuckle.AspNetCore 是一個(gè)開源的 .NET 包,用于為 ASP.NET Core Web API 生成美觀的、交互式的 OpenAPI 文檔(以前稱為 Swagger)。它是一個(gè)強(qiáng)大的工具,可以幫助開發(fā)人員快速生成易于理解和使用的 API 文檔。
官網(wǎng):https://github.com/domaindrivendev/Swashbuckle.AspNetCore/blob/master/README.md
Asp .Net Core 如何集成 Swagger?
要在 ASP.NET Core 項(xiàng)目中集成 Swashbuckle.AspNetCore,可以按照以下步驟進(jìn)行操作:
- 安裝 Swashbuckle.AspNetCore NuGet 包:
在 Visual Studio 中打開你的 ASP.NET Core 項(xiàng)目,并通過 NuGet 包管理器安裝 Swashbuckle.AspNetCore 包。
Install-Package Swashbuckle.AspNetCore
- 配置 Swashbuckle.AspNetCore:
在 Startup.cs 文件的 ConfigureServices 方法中,注冊 Swashbuckle 服務(wù)。
builder.Services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new OpenApiInfo
{
Title = "訂單服務(wù)",
Version = "v2",
Description = "訂單服務(wù)描述",
Contact = new OpenApiContact
{
Name = "robin",
Email = "2545233857@qq.com"
},
License = new OpenApiLicense
{
Name = "MIT",
Url = new Uri("https://www.cnblogs.com/vic-tory")
},
});
// 設(shè)置排序
options.OrderActionsBy((apiDesc) => $"{apiDesc.ActionDescriptor.RouteValues["controller"]}_{apiDesc.HttpMethod}");
//設(shè)置
var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SwaggerDemo.xml");
options.IncludeXmlComments(filePath);
});
更改 Swagger JSON 端點(diǎn)的路徑
默認(rèn)情況下,Swagger JSON 將在以下路由中公開 - “/swagger/{documentName}/swagger.json”。如有必要,您可以在啟用 Swagger 中間件時(shí)更改此設(shè)置。自定義路由必須包含該{documentName}參數(shù)。
app.UseSwagger(c =>
{
c.RouteTemplate = "api-docs/{documentName}/swagger.json";
});
注意:如果您使用 SwaggerUI 中間件,您還需要更新其配置以反映新端點(diǎn):
app.UseSwaggerUI(c =>
{
c.RoutePrefix = "swagger"; //指定路由前綴
c.SwaggerEndpoint("/api-docs/v1/swagger.json", "order api v1");
})
包含 XML 注釋中的描述
為了通過人性化的描述來增強(qiáng)生成的文檔,您可以使用 Xml 注釋來注釋控制器操作和模型,并配置 Swashbuckle 將這些注釋合并到輸出的 Swagger JSON 中:
打開項(xiàng)目的“屬性”對話框,單擊“構(gòu)建”選項(xiàng)卡并確保選中“XML 文檔文件”,或者將true元素添加到.csproj 項(xiàng)目文件的部分。這將在構(gòu)建時(shí)生成一個(gè)包含所有 XML 注釋的文件。
此時(shí),任何未使用 XML 注釋進(jìn)行注釋的類或方法都將觸發(fā)構(gòu)建警告。要抑制這種情況,請?jiān)趯傩詫υ捒虻摹耙种凭妗弊侄沃休斎刖娲a“1591”,或添加1591到.csproj 項(xiàng)目文件的部分。
配置 Swashbuckle 將文件上的 XML 注釋合并到生成的 Swagger JSON 中:
var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SwaggerDemo.xml");
options.IncludeXmlComments(filePath);
方法上
/// <summary>
/// 獲取天氣
/// </summary>
/// <param name="param">參數(shù)</param>
/// <returns>返回一個(gè)天氣集合</returns>
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get(string param)
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
添加 Jwt 驗(yàn)證
options.AddSecurityDefinition("bearerAuth", new OpenApiSecurityScheme
{
Type = SecuritySchemeType.Http,
Scheme = "bearer",
BearerFormat = "JWT",
Description = "請輸入Jwt 字符串"
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "bearerAuth" }
},
new string[] {}
}
});
第三方包
Package | Description |
---|---|
Swashbuckle.AspNetCore.Filters | Some useful Swashbuckle filters which add additional documentation, e.g. request and response examples, authorization information, etc. See its Readme for more details |
Unchase.Swashbuckle.AspNetCore.Extensions | Some useful extensions (filters), which add additional documentation, e.g. hide PathItems for unaccepted roles, fix enums for client code generation, etc. See its Readme for more details |
MicroElements.Swashbuckle.FluentValidation | Use FluentValidation rules instead of ComponentModel attributes to augment generated Swagger Schemas |
MMLib.SwaggerForOcelot | Aggregate documentations over microservices directly on Ocelot API Gateway |
封裝 Swagger 擴(kuò)展
SwaggerServiceExtensions文章來源:http://www.zghlxwxcb.cn/news/detail-800179.html
/// <summary>
/// Swagger 服務(wù)擴(kuò)展
/// </summary>
public static class SwaggerServiceExtensions
{
/// <summary>
/// 添加 Swagger 服務(wù)
/// </summary>
/// <param name="services"></param>
/// <param name="swaggerOptions"></param>
/// <returns></returns>
public static IServiceCollection AddMCodeSwagger(this IServiceCollection services, SwaggerOptions swaggerOptions)
{
services.AddSingleton(swaggerOptions);
SwaggerGenServiceCollectionExtensions.AddSwaggerGen(services, c =>
{
c.SwaggerDoc(swaggerOptions.ServiceName, swaggerOptions.ApiInfo);
if (swaggerOptions.XmlCommentFiles != null)
{
foreach (string xmlCommentFile in swaggerOptions.XmlCommentFiles)
{
string str = Path.Combine(AppContext.BaseDirectory, xmlCommentFile);
if (File.Exists(str)) c.IncludeXmlComments(str, true);
}
}
SwaggerGenOptionsExtensions.CustomSchemaIds(c, x => x.FullName);
c.AddSecurityDefinition("bearerAuth", new OpenApiSecurityScheme
{
Type = SecuritySchemeType.Http,
Scheme = "bearer",
BearerFormat = "JWT",
Description = "請輸入 bearer 認(rèn)證"
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "bearerAuth" }
},
new string[] {}
}
});
});
return services;
}
/// <summary>
/// 使用 Swagger UI
/// </summary>
/// <param name="app"></param>
/// <returns></returns>
public static IApplicationBuilder UseMCodeSwagger(this IApplicationBuilder app)
{
string serviceName = app.ApplicationServices.GetRequiredService<SwaggerOptions>().ServiceName;
SwaggerUIBuilderExtensions.UseSwaggerUI(SwaggerBuilderExtensions.UseSwagger(app), c =>
{
c.SwaggerEndpoint("/swagger/" + serviceName + "/swagger.json", "api." + serviceName);
});
return app;
}
}
SwaggerOptions文章來源地址http://www.zghlxwxcb.cn/news/detail-800179.html
/// <summary>
/// Swagger配置
/// </summary>
public class SwaggerOptions
{
/// <summary>
/// 服務(wù)名稱
/// </summary>
public string ServiceName { get; set; }
/// <summary>
/// API信息
/// </summary>
public OpenApiInfo ApiInfo { get; set; }
/// <summary>
/// Xml注釋文件
/// </summary>
public string[] XmlCommentFiles { get; set; }
/// <summary>
/// 構(gòu)造函數(shù)
/// </summary>
/// <param name="serviceName">服務(wù)名稱</param>
/// <param name="apiInfo">API信息</param>
/// <param name="xmlCommentFiles">Xml注釋文件</param>
public SwaggerOptions(string serviceName, OpenApiInfo apiInfo, string[] xmlCommentFiles = null)
{
ServiceName = !string.IsNullOrWhiteSpace(serviceName) ? serviceName : throw new ArgumentException("serviceName parameter not config.");
ApiInfo = apiInfo;
XmlCommentFiles = xmlCommentFiles;
}
}
到了這里,關(guān)于Asp .Net Core 系列:基于 Swashbuckle.AspNetCore 包 集成 Swagger的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!