Loading

.Net Core WebApi集成Swagger中间件

.Net Core WebApi集成Swagger中间件

简介

Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。

总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法、参数和模型紧密集成到服务器端的代码,允许 API 来始终保持同步。Swagger 让部署管理和使用功能强大的 API 从未如此简单。

前提

.Net Core的环境我相信大家都有

这里主要说一下Nuget包

Swashbuckle.AspNetCore               #核心库

Swashbuckle.AspNetCore.Annotations          #用于生成文档注释的属性拓展包

1 Install-Package Swashbuckle.AspNetCore
2 Install-Package Swashbuckle.AspNetCore.Annotations

初始化

Swagger的初始化的代码写在Startup.cs脚本里

 1 public class Startup
 2     {
 3         public Startup(IConfiguration configuration)
 4         {
 5             Configuration = configuration;
 6         }
 7  
 8         public IConfiguration Configuration { get; }
 9  
10         // This method gets called by the runtime. Use this method to add services to the container.
11         public void ConfigureServices(IServiceCollection services)
12         {
13             services.AddControllers();
14  
15             //注册Swagger服务
16             services.AddSwaggerGen(c =>
17             {
18                 //添加文档信息
19                 c.SwaggerDoc("v1", new OpenApiInfo
20                 {
21                     Version = "v1",
22                     Title = "Demo API",
23                     Description = "这是一个Demo Api 文档",
24                     Contact = new OpenApiContact
25                     {
26                         Name = "Lyon Nee",
27                         Email = "lyon.nee@outlook.com"
28                     }
29                 });
30                 c.EnableAnnotations();
31             });
32         }
33  
34         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
35         public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
36         {
37             if (env.IsDevelopment())
38             {
39                 app.UseDeveloperExceptionPage();
40             }
41  
42             //启动Swagger中间件
43             app.UseSwagger();
44             //配置SwaggerUI
45             app.UseSwaggerUI(c =>
46             {
47                 c.SwaggerEndpoint("/swagger/v1/swagger.json", "Demo API");
48                 c.RoutePrefix = string.Empty;
49             });
50  
51  
52             app.UseHttpsRedirection();
53  
54             app.UseRouting();
55  
56             app.UseAuthorization();
57  
58             app.UseEndpoints(endpoints =>
59             {
60                 endpoints.MapControllers();
61             });
62         }
63     }

检查

启动项目

我的程序端口监听是5001, 所以我打开 https://localhost:5001/index.html 就可以看到api文档页面了

像这样

添加注释

我使用默认的模版WeatherForecastController.cs进行了代码修改,如下

这里我们看到我没有使用以往或其他博主的 /// 三斜杠注释,而是使用了 Swashbuckle.AspNetCore.Annotations库的属性注释,这样的好处是不用生成.xml文档

 1 [ApiController]
 2     [Route("[controller]")]
 3     [SwaggerTag(".NetCore创建项目的Controller模版")]
 4     public class WeatherForecastController : ControllerBase
 5     {
 6         private readonly ILogger<WeatherForecastController> _logger;
 7  
 8         public WeatherForecastController(ILogger<WeatherForecastController> logger)
 9         {
10             _logger = logger;
11         }
12  
13         [SwaggerOperation(
14             Summary = "测试Get接口",
15             Description = "这是一个测试Get调用的方法"
16             )]
17         [SwaggerResponse(200, "调用成功", typeof(BaseResponse))]
18         [HttpGet, Route("TestGet")]
19         public IActionResult TestGet([FromQuery, SwaggerParameter("Get方法入参")] string input)
20         {
21             var result = "调用TestGet成功,输入的参数是:" + input;
22  
23             return Ok(new BaseResponse(200, "", result));
24         }
25  
26  
27         [SwaggerOperation(
28             Summary = "测试Post接口",
29             Description = "这是一个测试Post调用的方法"
30             )]
31         [SwaggerResponse(200, "调用成功", typeof(BaseResponse))]
32         [HttpPost, Route("TestPost")]
33         public IActionResult TestPost([FromBody, SwaggerRequestBody("Post方法入参")] PostDTO input)
34         {
35             var result = input.Data1.ToString() + input.Data2;
36  
37             return Ok(new BaseResponse(200, "", result));
38         }
39     }
40  
41     [SwaggerSchema("Post方法入参")]
42     public class PostDTO
43     {
44         [SwaggerSchema("int参数")]
45         public int Data1 { get; set; }
46  
47         [SwaggerSchema("string参数")]
48         public string Data2 { get; set; }
49     }
50  
51     public class BaseResponse
52     {
53         public int Code { get; set; }
54         public string Message { get; set; }
55         public object Data { get; set; }
56  
57         public BaseResponse(int code, string message = null, object data = null)
58         {
59             Code = code;
60             Message = message;
61             Data = data;
62         }
63     }

检查

再次启动项目,打开 https://localhost:5001/index.html 

像这样

测试方法调用

点击Try it out, 输入参数,点击Execute

像这样

测试Get方法

测试Post方法

这里可以看到,预期都是我们预期的结果

总结

到这里,我们的 .Net Core WebApi集成Swagger中间件 操作完成.

我们可以看到,集成Swagger之后,我们可以很方便的编写API文档,和测试API,这给我们的开发带来了极大的方便.

 

有问题或意见欢迎留言!

 个人小站:Lyon`s Home Page

posted @ 2021-03-31 09:29  灬倪先森丶  阅读(222)  评论(0编辑  收藏  举报