Microsoft DOc: Swagger/OpenAPI Swagger 项目已于 2015 年捐赠给 OpenAPI 计划,自此它被称为 OpenAPI。 是一个与语言无关的规范,用于描述 REST API。 它使计算机和用户无需直接访问源代码即可了解 REST API 的功能。
visual stuadio创建ASP.NET Core Web API项目模板,包含Enable OpenAPI support选项 即swagger页面
初始startup.cs的配置是1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebApplication1", Version = "v1" });
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebApplication1 v1"));
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
配置加载名为swagger.json的接口描述,记作WebApplication1 v1的接口文档
swagger.json不会自动生成 从controller获取接口文档由下述swagger的实现包完成
Swashbuckle.AspNetCore
启用xml注释
右键API项目 -> Properties -> Build -> Output
Output path 为空 即项目根目录
勾选XML documentation file 并命名1
2
3
4
5
6
7
8
9
10
11services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebApplication1", Version = "v1" });
c.DocInclusionPredicate((name, api) => api.HttpMethod != null);
// Locate the XML file being generated by ASP.NET
var xmlFiles = Directory.GetFiles(AppContext.BaseDirectory, "WebApplication1.API.xml", SearchOption.TopDirectoryOnly);
// Tell Swagger to use those XML comments.
xmlFiles.ToList().ForEach(xmlFile => c.IncludeXmlComments(xmlFile));
});
详情待续 参考Microsoft Doc:Swashbuckle入门