.NET Core利用swagger進(jìn)行API接口文檔管理的方法詳解
一、問題背景
隨著技術(shù)的發(fā)展,現(xiàn)在的開發(fā)模式已經(jīng)更多的轉(zhuǎn)向了前后端分離的模式,在前后端開發(fā)的過程中,聯(lián)系的方式也變成了API接口,但是目前項(xiàng)目中對(duì)于API的管理很多時(shí)候還是通過手工編寫文檔,每次的需求變更只要涉及到接口的變更,文檔都需要進(jìn)行額外的維護(hù),如果有哪個(gè)小伙伴忘記維護(hù),很多時(shí)候就會(huì)造成一連續(xù)的問題,那如何可以更方便的解決API的溝通問題?Swagger給我們提供了一個(gè)方式,由于目前主要我是投入在.NET Core項(xiàng)目的開發(fā)中,所以以.NET Core作為示例
二、什么是Swagger
Swagger可以從不同的代碼中,根據(jù)注釋生成API信息,swagger擁有強(qiáng)大的社區(qū),并且對(duì)于各種語言都支持良好,有很多的工具可以通過swagger生成的文件生成API文檔
三、.NET Core中使用
.NET Core中使用首先要用nuget引用Swashbuckle.AspNetCore,在startup.cs中加入如下代碼
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "Hello", Version = "v1" });
var basePath = PlatformServices.Default.Application.ApplicationBasePath;
var xmlPath = Path.Combine(basePath, "WebApplication2.xml");
c.IncludeXmlComments(xmlPath);
});
services.AddMvcCore().AddApiExplorer();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvcWithDefaultRoute();
app.UseSwagger(c =>
{
});
app.UseSwaggerUI(c =>
{
c.ShowExtensions();
c.ValidatorUrl(null);
c.SwaggerEndpoint("/swagger/v1/swagger.json", "test V1");
});
}
以上部分為加載swagger的代碼,位于startup.cs中,下面是controller代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication2.Controllers
{
/// <summary>
/// 測(cè)試信息
/// </summary>
[Route("api/[controller]/[action]")]
public class ValuesController : Controller
{
/// <summary>
/// 獲取所有信息
/// </summary>
/// <returns></returns>
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
/// <summary>
/// 根據(jù)ID獲取信息
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
// GET api/values/5
[HttpGet("{id}")]
public string Get(int id)
{
return "value";
}
/// <summary>
/// POST了一個(gè)數(shù)據(jù)信息
/// </summary>
/// <param name="value"></param>
// POST api/values
[HttpPost]
public void Post([FromBody]string value)
{
}
/// <summary>
/// 根據(jù)ID put 數(shù)據(jù)
/// </summary>
/// <param name="id"></param>
/// <param name="value"></param>
// PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody]string value)
{
}
/// <summary>
/// 根據(jù)ID刪除數(shù)據(jù)
/// </summary>
/// <param name="id"></param>
// DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
/// <summary>
/// 復(fù)雜數(shù)據(jù)操作
/// </summary>
/// <param name="id"></param>
// DELETE api/values/5
[HttpPost]
public namevalue test(namevalue _info)
{
return _info;
}
}
public class namevalue
{
/// <summary>
/// name的信息
/// </summary>
public String name { get; set; }
/// <summary>
/// value的信息
/// </summary>
public String value { get; set; }
}
}
接下來我們還需要在生成中勾上XML生成文檔,如圖所示

接下去我們可以運(yùn)行起來了,調(diào)試,瀏覽器中輸入http://localhost:50510/swagger/,這里端口啥的根據(jù)實(shí)際情況來,運(yùn)行效果如下圖所示:

可以看到swagger將方法上的注釋以及實(shí)體的注釋都抓出來了,并且顯示在swaggerui,整體一目了然,并且可以通過try it按鈕進(jìn)行簡(jiǎn)單的調(diào)試,但是在具體項(xiàng)目中,可能存在需要將某些客戶端信息通過header帶到服務(wù)中,例如token信息,用戶信息等(我們項(xiàng)目中就需要header中帶上token傳遞到后端),那針對(duì)于這種情況要如何實(shí)現(xiàn)呢?可以看下面的做法
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "Hello", Version = "v1" });
var basePath = PlatformServices.Default.Application.ApplicationBasePath;
var xmlPath = Path.Combine(basePath, "WebApplication2.xml");
c.IncludeXmlComments(xmlPath);
c.OperationFilter<AddAuthTokenHeaderParameter>();
});
services.AddMvcCore().AddApiExplorer();
}
public class AddAuthTokenHeaderParameter : IOperationFilter
{
public void Apply(Operation operation, OperationFilterContext context)
{
if (operation.Parameters == null)
{
operation.Parameters = new List<IParameter>();
}
operation.Parameters.Add(new NonBodyParameter()
{
Name = "token",
In = "header",
Type = "string",
Description = "token認(rèn)證信息",
Required = true
});
}
}
我們?cè)贑onfigureServices添加了OperationFilter<AddAuthTokenHeaderParameter>() ,通過這種方式我們可以在swagger中顯示token的header,并且進(jìn)行調(diào)試(如圖所示),AddAuthTokenHeaderParameter 的apply的屬性context中帶了controller以及action的各種信息,可以配合實(shí)際情況使用

四、與其他API管理工具結(jié)合
swagger強(qiáng)大的功能以及社區(qū)的力量,目前很多的API管理工具都支持YApi,目前我們使用的是由去哪兒開源的YApi,從圖中可以看到Y(jié)Api支持導(dǎo)入swagger生成的JSON文件,除該工具 之外DOClever(開源)也是一個(gè)不錯(cuò)的API管理工具,也支持Swagger文件導(dǎo)入(具體工具用法,大家可以去看他們的官網(wǎng))

源碼下載:demo地址
五、總結(jié)
Swagger是一個(gè)很好的工具,并且在前后端分離開發(fā)越來越流行的情況下,在后續(xù)的開發(fā)過程中,我覺得會(huì)扮演著越來越重要的作用,目前我們公司小的項(xiàng)目已經(jīng)準(zhǔn)備開始使用swagger+yapi進(jìn)行API的管理方式,而這篇文章也是這段時(shí)間抽空整理API管理的結(jié)果,希望可以幫助到大家,這里可能有很多不足的地方,歡迎大家拍磚,也希望可以跟大家一起進(jìn)步
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問大家可以留言交流,謝謝大家對(duì)腳本之家的支持。
相關(guān)文章
WEB上調(diào)用HttpWebRequest奇怪問題的解決方法
WEB上調(diào)用HttpWebRequest奇怪問題的解決方法...2007-04-04
asp.net下模態(tài)對(duì)話框關(guān)閉之后繼續(xù)執(zhí)行服務(wù)器端代碼的問題
asp.net下模態(tài)對(duì)話框關(guān)閉之后繼續(xù)執(zhí)行服務(wù)器端代碼的問題...2007-04-04
如何在ASP.NET Core中使用ViewComponent
這篇文章主要介紹了如何在ASP.NET Core中使用ViewComponent,幫助大家更好的理解和學(xué)習(xí)使用.net技術(shù),感興趣的朋友可以了解下2021-04-04
asp.net保存網(wǎng)上圖片到服務(wù)器的實(shí)例
本篇文章主要介紹了asp.net保存網(wǎng)上圖片到服務(wù)器,非常具有實(shí)用價(jià)值,需要的朋友可以參考下。2016-10-10
關(guān)于中g(shù)ridview 字符串截取的方法
在Gridview中,如果你的某一列字符串的長(zhǎng)度過長(zhǎng),不做處理的話.那么將顯示的奇丑無比,可以采取設(shè)置樣式,將其顯示為定長(zhǎng),可以在點(diǎn)擊查看的時(shí)候,在另一個(gè)頁面對(duì)其進(jìn)行顯示2013-06-06
ASP.NET CORE學(xué)習(xí)教程之自定義異常處理詳解
這篇文章主要給大家介紹了關(guān)于ASP.NET CORE學(xué)習(xí)教程之自定義異常處理的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-01-01

