ASP.NET Core 3.1使用Swagger

1、什麼是Swagger

隨着技術的不斷方法,如今的網站開發基本都是使用先後端分離的模式,這樣使前端開發者和後端開發者只須要專一本身擅長的便可。但這種方式會存在一種問題:先後端經過API接口的方式進行調用,接口文檔的好壞能夠決定開發的進度。之前若是使用Word的形式提供接口文檔,或多或少的都會存在各類問題。前端抱怨說後端給的接口文檔與實際狀況不一致。然後端開發人員又以爲編寫以及維護接口文檔很費精力,文檔常常不能及時更新,致使前端看到的仍是舊的接口文檔。這時候就須要使用Swagger了。html

那麼什麼是Swagger呢?Swagger是最流行的API開發工具,它遵循了OpenAPI規範,能夠根據API接口自動生成在線文檔,這樣就能夠解決文檔更新不及時的問題。它能夠貫穿於整個API生態,好比API的設計、編寫API文檔等。並且Swagger仍是一種通用的、與具體編程語言無關的API描述規範。前端

有關更多Swagger的介紹,能夠參考Swagger官網,官網地址:https://swagger.io/數據庫

2、ASP.NET Core中使用Swagger

這裏使用最新的ASP.NET Core 3.1建立WebAPI接口。關於如何建立WebAPI這裏不在描述。建立後的WebAPI項目結構以下:編程

一、添加Swagger

直接在NuGet裏面搜索Swashbuckle.AspNetCore包進行安裝:json

二、添加服務

在Startup類的ConfigureServices方法裏面注入服務:後端

public void ConfigureServices(IServiceCollection services) { // 添加Swagger
    services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "API Demo", Version = "v1" }); }); services.AddControllers(); }

三、添加中間件

在Startup類的Configure方法裏面添加Swagger有關的中間件:api

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(); }); } 

四、添加控制器

新建一個控制器,裏面包括基礎的增刪改查方法:app

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可使用一樣的方式進行測試。 

3、總結

上面簡單介紹了什麼是Swagger,以及如何利用Swagger進行調試,這樣只須要啓動程序便可,不須要在額外的使用Postman進行測試。使用Swagger能夠保持接口文檔可以及時更新。

相關文章
相關標籤/搜索