0x00 安裝 Swashbuckle 6.0
打開程序包管理器控制台,輸入:
Install-Package Swashbuckle -Pre
0x01 配置 Startup.cs
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddApplicationInsightsTelemetry(Configuration);
services.AddMvc();
// 下面是具體的配置
services.AddSwaggerGen(c =>
{
c.SingleApiVersion(new Info
{
Version = "v1", // 這個屬性必須要填,否則會引發一個異常
Title = "BookList API 文檔",
Description = "書單的 API 文檔"
});
});
services.ConfigureSwaggerGen(c =>
{
// 配置生成的 xml 注釋文檔路徑
c.IncludeXmlComments(GetXmlCommentsPath());
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseApplicationInsightsRequestTelemetry();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseApplicationInsightsExceptionTelemetry();
app.UseStaticFiles();
app.UseSwagger();
app.UseSwaggerUi("doc/api"); // 配置 api 文檔的訪問路徑
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
下面是獲取xml文檔路徑的方法
private string GetXmlCommentsPath()
{
var app = PlatformServices.Default.Application;
return Path.Combine(app.ApplicationBasePath, Path.ChangeExtension(app.ApplicationName, "xml"));
}
0x03 配置項目屬性
在 VS 的菜單中,項目 -- 屬性 -- 生成 -- Output -- XML documentation file 打上勾
0x04 盡情使用生成的文檔吧!
訪問 localhost:*****/doc/api 就可以看到生成的文檔
這里的路徑是我在上面配置的,默認的路徑是 swagger/ui