- 添加Swashbuckle.AspNetCore
- startup ConfigureServices添加Swagger配置
- 此步骤之前先右键站点点击属性在生成面板设置
- 取消显示警告添加;1591 这个是取消vs的注释提醒
- 输出板块勾选 XML文档文件选项
#region Swagger services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo() { Title = "数据服务API", Version = "v1" });
c.DocumentFilter<SwaggerIgnoreFilter>(); var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";//开启xml注释 var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); }); #endregion
- startup Configure 添加swagger配置
#region Swagger app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "数据服务API"); c.RoutePrefix = "doc"; //路由前缀 }); #endregion
- 标记为ApiController 标签的页面配置好Route后就能自动生成文档了
- 最终访问地址http://localhost:8066/doc/index.html
- 一些扩展过滤不需要显示的接口
using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerGen; using System.Collections.Generic; using System.Linq; namespace BBSS.Basic.Host { /// <summary> /// 隐藏不需要显示的接口 /// </summary> public class SwaggerIgnoreFilter : IDocumentFilter { public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context) { var startRoutes = new List<string> { "v1/client", "v1/token" }; var ignoreApis = context.ApiDescriptions.Where(wh => !startRoutes.Any(r => wh.RelativePath.ToLower().StartsWith(r))); if (ignoreApis != null) { foreach (var ignoreApi in ignoreApis) { swaggerDoc.Paths.Remove("/" + ignoreApi.RelativePath); } } } } }