.NetCore學習筆記:六、Swagger API介面文件工具
阿新 • • 發佈:2020-07-29
Swagger一個優秀的Api介面文件生成工具。Swagger可以可以動態生成Api介面文件,有效的降低前後端人員關於Api介面的溝通成本,促進專案高效開發。
1、使用NuGet安裝最新的包:Swashbuckle.AspNetCore。
2、編輯專案檔案(NetCoreTemplate.Web.csproj),配置Xml文件生成目錄。
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> <DocumentationFile>bin\Debug\netcoreapp3.1\NetCoreTemplate.Web.xml</DocumentationFile> <OutputPath>bin\Debug\netcoreapp3.1\</OutputPath> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'"> <DocumentationFile>bin\Release\netcoreapp3.1\NetCoreTemplate.Web.xml</DocumentationFile><OutputPath>bin\Release\netcoreapp3.1\</OutputPath> </PropertyGroup>
3、在專案中註冊Swagger,新增一個文件資訊和匯入Xml檔案資訊。
// 註冊Swagger服務 services.AddSwaggerGen(c => { // 新增文件資訊 c.SwaggerDoc("v1", new OpenApiInfo { Title = "NetCoreTemplate Api", Version = "v1" }); //匯入XML檔案資訊 var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); });
4、新增Swagger中介軟體和Page UI。
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "NetCoreTemplate V1");
});
這樣配置就完成了,啟動程式檢驗一下成果。