一,我们新建.NET Core 3.0的API项目
二,neget包Swashbuckle.AspNetCore
三,修改Startup文件
public void ConfigureServices(IServiceCollection services) { services.AddControllers(); //添加Swagger services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Version = "v1", Title = "Api Swagger", Description = "基于.NET Core 3.0 的Api Swagger" }); // 加载程序集的xml描述文档 var baseDirectory = System.AppDomain.CurrentDomain.BaseDirectory; var xmlFile = System.AppDomain.CurrentDomain.FriendlyName + ".xml"; var xmlPath = Path.Combine(baseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); }); }
添加
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseAuthorization(); //启用中间件服务生成Swagger作为JSON终结点 app.UseSwagger(); //启用中间件服务对swagger-ui,指定Swagger JSON终结点 app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "Vedm API V1"); }); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }
添加以上代码,然后运行程序发现报错如下
四,原因是根目录下没有生成SwapperApi.xml文件,新建文件,格式如下
<?xml version="1.0"?> <doc> <assembly> <name>SwapperApi</name> </assembly> <members> <member> <summary> ApiController是被swagger标识的特性 </summary> </member> </members> </doc>
PS,XML文件名是项目命名,原因是配置里
var baseDirectory = System.AppDomain.CurrentDomain.BaseDirectory; var xmlFile = System.AppDomain.CurrentDomain.FriendlyName + ".xml";
决定的
五,再次启动,访问http://localhost:52522/swagger/index.html
成功!!