網站首頁 編程語言 正文
一、什么是Swagger
隨著技術的不斷方法,現在的網站開發(fā)基本都是使用前后端分離的模式,這樣使前端開發(fā)者和后端開發(fā)者只需要專注自己擅長的即可。但這種方式會存在一種問題:前后端通過API接口的方式進行調用,接口文檔的好壞可以決定開發(fā)的進度。以前如果使用Word的形式提供接口文檔,或多或少的都會存在各種問題。前端抱怨說后端給的接口文檔與實際情況不一致。而后端開發(fā)人員又覺得編寫以及維護接口文檔很費精力,文檔經常不能及時更新,導致前端看到的還是舊的接口文檔。這時候就需要使用Swagger了。
那么什么是Swagger呢?Swagger是最流行的API開發(fā)工具,它遵循了OpenAPI規(guī)范,可以根據API接口自動生成在線文檔,這樣就可以解決文檔更新不及時的問題。它可以貫穿于整個API生態(tài),比如API的設計、編寫API文檔等。而且Swagger還是一種通用的、與具體編程語言無關的API描述規(guī)范。
有關更多Swagger的介紹,可以參考Swagger官網,官網地址:https://swagger.io/
二、ASP.NET Core中使用Swagger
這里使用最新的ASP.NET Core 3.1創(chuàng)建WebAPI接口。關于如何創(chuàng)建WebAPI這里不在描述。創(chuàng)建后的WebAPI項目結構如下:
1、添加Swagger
直接在NuGet里面搜索Swashbuckle.AspNetCore包進行安裝:
2、添加服務
在Startup類的ConfigureServices方法里面注入服務:
public void ConfigureServices(IServiceCollection services) { // 添加Swagger services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "API Demo", Version = "v1" }); }); services.AddControllers(); }
3、添加中間件
在Startup類的Configure方法里面添加Swagger有關的中間件:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } // 添加Swagger有關中間件 app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "API Demo v1"); }); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }
4、添加控制器
新建一個控制器,里面包括基礎的增刪改查方法:
using Microsoft.AspNetCore.Mvc; namespace SwaggerDemo.Controllers { [Route("api/student")] [ApiController] public class StudentController : ControllerBase { [HttpGet] public string Get() { return "Tom"; } [HttpPost] public void Post() { } [HttpPut] public void Put() { } [HttpDelete] public void Delete() { } } }
運行程序,修改一下url地址:
http://localhost:5000/swagger/index.html
如下圖所示:
這樣就可以看到接口了。但這樣還不是我們最終想要的結果,我們想知道每個方法的注釋和方法參數的注釋,這就需要對接口做XML注釋了。首先安裝Microsoft.Extensions.PlatformAbstractions包:
然后修改ConfigureServices方法,增加下面的方法:
public void ConfigureServices(IServiceCollection services) { #region 添加Swagger services.AddSwaggerGen(options => { options.SwaggerDoc("v1",new OpenApiInfo { Title = "My API", Version = "v1" }); // 獲取xml文件名 var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; // 獲取xml文件路徑 var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); // 添加控制器層注釋,true表示顯示控制器注釋 options.IncludeXmlComments(xmlPath, true); }); #endregion services.AddControllers(); }
然后給新建的接口添加注釋:
using Microsoft.AspNetCore.Mvc; namespace SwaggerDemo.Controllers { /// <summary> /// 學生控制器 /// </summary> [Route("api/student")] [ApiController] public class StudentController : ControllerBase { /// <summary> /// 獲取所有學生 /// </summary> /// <returns></returns> [HttpGet] public string Get() { return "Tom"; } /// <summary> /// 新增學生 /// </summary> [HttpPost] public void Post() { } /// <summary> /// 修改學生信息 /// </summary> [HttpPut] public void Put() { } /// <summary> /// 刪除學生信息 /// </summary> [HttpDelete] public void Delete() { } } }
項目右鍵,選擇屬性,勾選“XML文檔文件”,如下圖所示:
在運行程序:
可以看到,剛才在控制器上面添加的注釋信息都顯示出來了。這樣前端就可以直接查看接口文檔了。
Swagger除了可以顯示接口注釋以外,還可以進行調試,以前調試都是使用Postman,我們也可以直接使用Swagger進行調試。新添加一個Student類:
namespace SwaggerDemo { public class Student { public int ID { get; set; } public string Name { get; set; } public int Age { get; set; } } }
然后新建一個集合,里面添加一些Student的數據,模擬數據庫操作:
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace SwaggerDemo { public class DataHelper { public static List<Student> ListStudent = new List<Student>(); public static List<Student> GetStudent() { for (int i = 0; i < 5; i++) { Student student = new Student(); student.ID = i; student.Name = $"測試_{i}"; student.Age = 20 + i; ListStudent.Add(student); } return ListStudent; } } }
然后修改Student控制器:
using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; namespace SwaggerDemo.Controllers { /// <summary> /// 學生控制器 /// </summary> [Route("api/student")] [ApiController] public class StudentController : ControllerBase { /// <summary> /// 獲取所有學生 /// </summary> /// <returns></returns> [HttpGet] public List<Student> Get() { return DataHelper.GetStudent(); } /// <summary> /// 新增學生 /// </summary> /// <param name="entity">學生實體</param> /// <returns></returns> [HttpPost] public List<Student> Post(Student entity) { DataHelper.ListStudent.Add(entity); return DataHelper.ListStudent; } /// <summary> /// 修改學生信息 /// </summary> /// <param name="entity">學生實體</param> /// <returns></returns> [HttpPut] public List<Student> Put(Student entity) { for (int i = 0; i < DataHelper.ListStudent.Count; i++) { if (DataHelper.ListStudent[i].ID == entity.ID) { DataHelper.ListStudent[i].Name = entity.Name; DataHelper.ListStudent[i].Age = entity.Age; break; } } return DataHelper.ListStudent; } /// <summary> /// 刪除學生信息 /// </summary> /// <param name="id">學生Id</param> /// <returns></returns> [HttpDelete] public List<Student> Delete(int id) { for (int i = 0; i < DataHelper.ListStudent.Count; i++) { if(DataHelper.ListStudent[i].ID == id) { DataHelper.ListStudent.Remove(DataHelper.ListStudent[i]); break; } } return DataHelper.ListStudent; } } }
運行程序:
這時候是不能輸入的,只能查看,點擊右上角的“Try it out”:
這時會變成Cancel,點擊Cancel會回到Try it out:
我們點擊Execute執(zhí)行:
下面會列出執(zhí)行結果:
這樣就完成了GET方法的調試。這是無參數方法的調試,如果有參數的方法怎么調試呢?我們以POT方法為例。我們點開POST方法:
然后點擊“Tty it out”,可以變成輸入狀態(tài),輸入參數,點擊“Execute”按鈕執(zhí)行:
最后在下面就會輸出結果:
PUT和DELETE可以使用同樣的方式進行測試。
三、總結
上面簡單介紹了什么是Swagger,以及如何利用Swagger進行調試,這樣只需要啟動程序即可,不需要在額外的使用Postman進行測試。使用Swagger可以保持接口文檔能夠及時更新。
原文鏈接:https://www.cnblogs.com/dotnet261010/p/12425572.html
相關推薦
- 2022-10-01 Python中的閉包使用及作用_python
- 2022-12-11 C語言中求解圖形的問題_C 語言
- 2022-06-28 Python技法之簡單遞歸下降Parser的實現方法_python
- 2022-12-12 Android?Cocos?Creator游戲開發(fā)平臺打包優(yōu)化實現方案_Android
- 2023-07-18 Spring 中的 Service 有多個實現類如何注入
- 2021-12-03 C++學習之線程詳解_C 語言
- 2022-05-25 Python異常處理如何才能寫得優(yōu)雅(retrying模塊)_python
- 2023-01-31 iOS?底層alloc?init?new?源碼流程示例分析_IOS
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發(fā)現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支