1、先通过NuGet安装Swashbuckle.AspNetCore ,支持.NET core,版本是4.0.1,以上版本好像有些功能不支持
2、startup文件里注入swagger,ConfigureServices 方法注入swagger内容,
#region 添加SwaggerUI services.AddSwaggerGen(options => { options.SwaggerDoc("v1", new Info { Title = "钉钉测试文档", Version = "v1" }); //Determine base path for the application. var basePath = PlatformServices.Default.Application.ApplicationBasePath; //Set the comments path for the swagger json and ui. var xmlPath = Path.Combine(basePath, "DingDingTest.xml"); options.IncludeXmlComments(xmlPath); }); #endregion
以上最坑地方是PlatformServices这个类找不到,查了半天资料才知道需要引入dll,通过nuget添加程序集,Microsoft.Extensions.PlatformAbstractions
DingDingTest.xml 文件通过属性生成里打钩自动生成xml文件
管道里增加swagger管道,
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "钉钉测试 API V1");
});
运行报错,
Fetch error
undefined /swagger/v1/swagger.json
swagger.JSON是动态生成的,无法手工找到,找了半天才发现,有一个方法我没有设置路由造成生成json文件报错,不是找不到的问题,所以所有方法都要设置路由,不然会报这种莫名的错误
地址栏输入地址,
测试成功,搭建成功,但是每次都要输入地址才会出现,现在默认显示swagger,修改launchsettings.json文件
1 { 2 "iisSettings": { 3 "windowsAuthentication": false, 4 "anonymousAuthentication": true, 5 "iisExpress": { 6 "applicationUrl": "http://localhost:12569/", 7 "sslPort": 0 8 } 9 }, 10 "profiles": { 11 "IIS Express": { 12 "commandName": "IISExpress", 13 "launchBrowser": true, 14 "launchUrl": "swagger/ui", 15 "environmentVariables": { 16 "ASPNETCORE_ENVIRONMENT": "Development" 17 } 18 }, 19 "DataSaas": { 20 "commandName": "Project", 21 "launchBrowser": false, 22 "launchUrl": "swagger/ui", 23 "environmentVariables": { 24 "ASPNETCORE_ENVIRONMENT": "Development" 25 }, 26 "applicationUrl": "http://localhost:12570/" 27 } 28 } 29 }