Understanding Swagger
Swagger is a standardized and complete framework for generating, description, and visualization calls for RESTful Web services. The overall objective is to make the client and the file system as a server at the same rate updates. Methods, parameters and models are tightly integrated into the file server-side code that allows the API to always be in sync.
effect:
- Document interface automatically generates online.
- function test.
Why use Swagger as REST APIs document generation tool
- Swagger can generate an interactive console's API, developers can be used to quickly learn and try API.
- Swagger client SDK code can be generated for implementing a variety of different platforms.
- Swagger file can be generated automatically from code comments on many different platforms.
- Swagger has a strong community, there are many powerful contributors.
Installation package Nuget search Swashbuckle.AspNetCore
Because it is .NetCore3.0, so be sure to check include a preview release, install the latest pre-release version 5.0.0-rc4, do not install the latest stable version. Stable error.
Stable error message:
1 Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: 2 Swashbuckle.AspNetCore.Swagger.ISwaggerProvider Lifetime: Transient ImplementationType: 3 Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator': Failed to compare two elements in the array.) 4 (Error while validating the service descriptor 'ServiceType: Swashbuckle.AspNetCore.SwaggerGen.ISchemaRegistryFactory Lifetime: 5 Transient ImplementationType: Swashbuckle.AspNetCore.SwaggerGen.SchemaRegistryFactory': Failed to compare two elements in the array.)
The solution is to install version 3.0 now preview release 5.0.0-rc4
Swagger arranged in .NetCore3.0 also changes in
the previous
1 services.AddSwaggerGen(c => 2 { 3 c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" }); 4 });
Change
1 services.AddSwaggerGen(c => 2 { 3 c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" }); 4 });
The biggest change is the Info Here, in the previous version 2.0 is managed by the Swagger. In version 3.0 is OpenApi Unified Change Management, OpenApi introduced as a global tool for .NET Core OpenAPI references within the project management in the official document.
Reference Address: (https://docs.microsoft.com/zh-cn/aspnet/core/web-api/microsoft.dotnet-openapi?view=aspnetcore-3.1 "OpenAPI use tools to develop ASP.NET Core Application")
So after you have added Swagger package, also add Microsoft.OpenApi package in the project
Registration Swagger
1 public void ConfigureServices(IServiceCollection services) 2 { 3 4 services.AddControllers(); 5 6 services.AddSwaggerGen(c => 7 { 8 c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" }); 9 }); 10 11 }
配置Swagger UI
1 public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 2 { 3 if (env.IsDevelopment()) 4 { 5 app.UseDeveloperExceptionPage(); 6 } 7 app.UseHttpsRedirection(); 8 app.UseRouting(); 9 app.UseAuthorization(); 10 //启用Swagger 11 app.UseSwagger(); 12 //配置Swagger UI 13 app.UseSwaggerUI(c => 14 { 15 c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API"); //注意中间段v1要和上面SwaggerDoc定义的名字保持一致 16 }); 17 app.UseEndpoints(endpoints => 18 { 19 endpoints.MapControllers(); 20 }); 21 }
启动项目
CTRL+F5启动项目,并导航到 http://localhost:port/swagger 通过Swagger UI游览API文档
Swagger的高级用法(自定义扩展)
在 AddSwaggerGen 方法的进行如下的配置操作会添加诸如作者、许可证和说明信息等:
1 services.AddSwaggerGen(c => 2 { 3 c.SwaggerDoc("v1", new OpenApiInfo 4 { 5 Title = "My API", 6 Version = "v1", 7 Description = "API文档描述", 8 Contact = new OpenApiContact 9 { 10 Email = "[email protected]", 11 Name = "开源NetCore", 12 Url = new Uri("http://www.netcore.pub/") 13 }, 14 License = new OpenApiLicense 15 { 16 Name = "许可证名称", 17 Url = new Uri("http://www.netcore.pub/") 18 } 19 }); 20 });
Swagger UI 显示版本的信息如下图所示
为API接口方法添加注释
大家先点开API,展开如下图所示,可是没有注释呀,怎么添加注释呢?
按照下列代码所示用三个/添加文档注释,如下所示
1 /// <summary> 2 /// 这是一个API注释 3 /// </summary> 4 /// <returns></returns> 5 [HttpGet] 6 public IEnumerable<WeatherForecast> Get() 7 { 8 var rng = new Random(); 9 return Enumerable.Range(1, 5).Select(index => new WeatherForecast 10 { 11 Date = DateTime.Now.AddDays(index), 12 TemperatureC = rng.Next(-20, 55), 13 Summary = Summaries[rng.Next(Summaries.Length)] 14 }) 15 .ToArray(); 16 }
然后运行项目,回到Swagger UI中去查看注释是否出现了呢
还是没出现?一脸懵逼??? 别急往下看!
启用XML注释
可使用以下方法启用 XML 注释:
右键单击“解决方案资源管理器”中的项目,然后选择“属性”
查看“生成”选项卡的“输出”部分下的“XML 文档文件”框
启用 XML 注释后会为未记录的公共类型和成员提供调试信息。如果出现很多警告信息 例如,以下消息指示违反警告代码 1591:
1 warning CS1591: Missing XML comment for publicly visible type or member 'TodoController.GetAll()'
如果你有强迫症,想取消警告怎么办呢?可以按照下图所示进行取消
注意上面生成的xml文档文件的路径,
注意:
1.对于 Linux 或非 Windows 操作系统,文件名和路径区分大小写。 例如,“Kylin.Wiki.xml”文件在 Windows 上有效,但在 CentOS 上无效。
2.获取应用程序路径,建议采用Path.GetDirectoryName(typeof(Program).Assembly.Location)这种方式或者·AppContext.BaseDirectory这样来获取
1 services.AddSwaggerGen(c => 2 { 3 c.SwaggerDoc("v1", new OpenApiInfo 4 { 5 Title = "My API", 6 Version = "v1", 7 Description = "API文档描述", 8 Contact = new OpenApiContact 9 { 10 Email = "[email protected]", 11 Name = "开源NetCore", 12 Url = new Uri("http://www.netcore.pub/") 13 }, 14 License = new OpenApiLicense 15 { 16 Name = "许可证名称", 17 Url = new Uri("http://www.netcore.pub/") 18 } 19 }); 20 // 为 Swagger JSON and UI设置xml文档注释路径 21 var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location);//获取应用程序所在目录(绝对,不受工作目录影响,建议采用此方法获取路径) 22 var xmlPath = Path.Combine(basePath, "Kylin.Wiki.xml"); 23 c.IncludeXmlComments(xmlPath); 24 });
重新生成并运行项目查看一下注释出现了没有
通过上面的操作可以总结出,Swagger UI 显示上述注释代码的元素的内部文本作为api大的注释!
当然你还可以将 remarks 元素添加到 Get 操作方法文档。 它可以补充元素中指定的信息,并提供更可靠的 Swagger UI。 元素内容可包含文本、JSON 或 XML。 代码如下:
1 /// <summary> 2 /// 这是一个带参数的get请求 3 /// </summary> 4 /// <remarks> 5 /// 例子: 6 /// Get api/Values/1 7 /// </remarks> 8 /// <param name="id">主键</param> 9 /// <returns>测试字符串</returns> 10 public ActionResult<string> Get(int id) 11 { 12 return $"你请求的 id 是 {id}"; 13 }
重新生成下项目,当好到SwaggerUI看到如下所示:
描述响应类型
接口使用者最关心的就是接口的返回内容和响应类型啦。下面展示一下201和400状态码的一个简单例子:
我们需要在我们的方法上添加:
[ProducesResponseType(201)]
[ProducesResponseType(400)]
然后添加相应的状态说明:返回value字符串如果id为空
最终代码应该是这个样子:
1 /// <summary> 2 /// 这是一个带参数的get请求 3 /// </summary> 4 /// <remarks> 5 /// 例子: 6 /// Get api/Values/1 7 /// </remarks> 8 /// <param name="id">主键</param> 9 /// <returns>测试字符串</returns> 10 /// <response code="201">返回value字符串</response> 11 /// <response code="400">如果id为空</response> 12 // GET api/values/2 13 [HttpGet("{id}")] 14 [ProducesResponseType(201)] 15 [ProducesResponseType(400)] 16 public ActionResult<string> Get(int id) 17 { 18 return $"你请求的 id 是 {id}"; 19 }
效果如下所示
状态相应效果
使用SwaggerUI测试api接口
下面我们通过一个小例子通过SwaggerUI调试下接口吧
点击一个需要测试的API接口,然后点击Parameters左右边的“Try it out ” 按钮
在出现的参数文本框中输入参数,如下图所示的,输入参数2
点击执行按钮,会出现下面所示的格式化后的Response,如下图所示
好了,今天的在ASP.NET Core WebApi 3.0 中使用Swagger生成api说明文档教程就到这里了。希望能够对大家学习在ASP.NET Core中使用Swagger生成api文档有所帮助!
「开源NetCore,如果觉得我的文章对您有用,请帮助本站成长」
除非注明,文章均由开源 NetCore 整理发布,欢迎转载。
转载请注明本文地址:http://www.netcore.pub/167.html
站长会将优质文章在各大平台同步更新、推送,欢迎大家访问、订阅: