一、什么是Swagger
隨着技術的不斷方法,現在的網站開發基本都是使用前后端分離的模式,這樣使前端開發者和后端開發者只需要專注自己擅長的即可。但這種方式會存在一種問題:前后端通過API接口的方式進行調用,接口文檔的好壞可以決定開發的進度。以前如果使用Word的形式提供接口文檔,或多或少的都會存在各種問題。前端抱怨說后端給的接口文檔與實際情況不一致。而后端開發人員又覺得編寫以及維護接口文檔很費精力,文檔經常不能及時更新,導致前端看到的還是舊的接口文檔。這時候就需要使用Swagger了。
那么什么是Swagger呢?Swagger是最流行的API開發工具,它遵循了OpenAPI規范,可以根據API接口自動生成在線文檔,這樣就可以解決文檔更新不及時的問題。它可以貫穿於整個API生態,比如API的設計、編寫API文檔等。而且Swagger還是一種通用的、與具體編程語言無關的API描述規范。
有關更多Swagger的介紹,可以參考Swagger官網,官網地址:https://swagger.io/
二、ASP.NET Core中使用Swagger
這里使用最新的ASP.NET Core 3.1創建WebAPI接口。關於如何創建WebAPI這里不在描述。創建后的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執行:

下面會列出執行結果:

這樣就完成了GET方法的調試。這是無參數方法的調試,如果有參數的方法怎么調試呢?我們以POT方法為例。我們點開POST方法:

然后點擊“Tty it out”,可以變成輸入狀態,輸入參數,點擊“Execute”按鈕執行:

最后在下面就會輸出結果:

PUT和DELETE可以使用同樣的方式進行測試。
三、總結
上面簡單介紹了什么是Swagger,以及如何利用Swagger進行調試,這樣只需要啟動程序即可,不需要在額外的使用Postman進行測試。使用Swagger可以保持接口文檔能夠及時更新
