新聞中心
本文轉載自微信公眾號「碼農(nóng)讀書」,作者碼農(nóng)讀書 。轉載本文請聯(lián)系碼農(nóng)讀書公眾號。

創(chuàng)新互聯(lián)公司是一家集網(wǎng)站建設,青陽企業(yè)網(wǎng)站建設,青陽品牌網(wǎng)站建設,網(wǎng)站定制,青陽網(wǎng)站建設報價,網(wǎng)絡營銷,網(wǎng)絡優(yōu)化,青陽網(wǎng)站推廣為一體的創(chuàng)新建站企業(yè),幫助傳統(tǒng)企業(yè)提升企業(yè)形象加強企業(yè)競爭力??沙浞譂M足這一群體相比中小企業(yè)更為豐富、高端、多元的互聯(lián)網(wǎng)需求。同時我們時刻保持專業(yè)、時尚、前沿,時刻以成就客戶成長自我,堅持不斷學習、思考、沉淀、凈化自己,讓我們?yōu)楦嗟钠髽I(yè)打造出實用型網(wǎng)站。
大家在開發(fā)完 webapi 后,經(jīng)常為了方便接口雙方對接,需要將 webapi 接口文檔化,那有沒有什么快捷可交互的文檔呢?可以利用快捷工具 Swagger,它的可視化 UI 可輕松助你 API 文檔化的同時還方便測試 API。
Swashbuckle 就是一個用于生成 Swagger 文檔的開源工具包,這篇文章將會討論如何利用 Swashbuckle 來為你的 Restful API 生成可交互的文檔。
安裝 Swagger 中間件
要想利用 Swagger 文檔化,需要 nuget 引用 Swashbuckle.AspNetCore 包,還可以通過 Visual Studio 2019 的 NuGet package manager 可視化界面安裝 或者 通過 NuGet package manager 命令行工具輸入以下命令:
- dotnet add package Swashbuckle.AspNetCore
配置 Swagger 中間件
為了配置 Swagger,在 Startup.ConfigureServices 方法中添加如下代碼,注意下面的 AddSwaggerGen 方法是用于給 API 文檔 添加一些元數(shù)據(jù)。
- services.AddSwaggerGen(c =>
- {
- c.SwaggerDoc("v1", new Info
- {
- Version = "v1",
- Title = "Swagger Demo",
- Description = "Swagger Demo for ValuesController",
- TermsOfService = "None",
- Contact = new Contact() { Name = "Joydip Kanjilal",
- Email = "joydipkanjilal@yahoo.com",
- Url = "www.google.com" }
- });
- });
接下來就要啟動 Swagger了,在 Startup.Configure 方法下添加如下代碼:
- app.UseSwagger();
- app.UseSwaggerUI(c =>
- {
- c.SwaggerEndpoint("/swagger/v1/swagger.json", "v1");
- });
為了完整性,下面是 Startup 中的所有代碼清單。
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.DependencyInjection;
- using Swashbuckle.AspNetCore.Swagger;
- namespace IDGSwaggerDemo
- {
- public class Startup
- {
- public Startup(IConfiguration configuration)
- {
- Configuration = configuration;
- }
- public IConfiguration Configuration { get; }
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddMvc().SetCompatibilityVersion
- (CompatibilityVersion.Version_2_2);
- services.AddSwaggerGen(c =>
- {
- c.SwaggerDoc("v1", new Info
- {
- Version = "v1",
- Title = "Swagger Demo",
- Description = "Swagger Demo for ValuesController",
- TermsOfService = "None",
- Contact = new Contact() { Name = "Joydip Kanjilal",
- Email = "joydipkanjilal@yahoo.com",
- Url = "www.google.com"
- }
- });
- });
- }
- public void Configure(IApplicationBuilder app,
- IHostingEnvironment env)
- {
- if (env.IsDevelopment())
- {
- app.UseDeveloperExceptionPage();
- }
- app.UseMvc();
- app.UseSwagger();
- app.UseSwaggerUI(c =>
- {
- c.SwaggerEndpoint("/swagger/v1/swagger.json", "v1");
- });
- }
- }
- }
瀏覽 Swagger UI
現(xiàn)在我們運行一下應用程序來瀏覽一下 Swagger UI 地址,可以看到 UI 界面如下圖所示,圖中不同的 Http 請求使用了不同的顏色進行標識,你甚至可以在UI上直接測試不同的 api 接口。
在 Action 方法上創(chuàng)建xml注解
到目前為止一切順利,在剛才生成的 swagger 文檔中,并沒有看到 5 個 api 接口的任何注解,這就不優(yōu)雅了,如果想要在 swagger 文檔上增加 xml 注解,簡單粗暴的做法可以直接在 Controller.Action 頂部寫上注解信息。
接下來在 ValuesController 下的每一個 Action 上都加上注解,下面就是修改后的 ValueController。
- [Route("api/[controller]")]
- [ApiController]
- public class ValuesController : ControllerBase
- {
- ///
- /// Get action method without any argument
- ///
- ///
- [HttpGet]
- public ActionResult
> Get() - {
- return new string[] { "value1", "value2" };
- }
- ///
- /// Get action method that accepts an integer as an argument
- ///
- ///
- ///
- [HttpGet("{id}")]
- public ActionResult
Get(int id) - {
- return "value";
- }
- ///
- /// Post action method to add data
- ///
- ///
- [HttpPost]
- public void Post([FromBody] string value)
- {
- }
- ///
- /// Put action method to modify data
- ///
- ///
- ///
- [HttpPut("{id}")]
- public void Put(int id, [FromBody] string value)
- {
- }
- ///
- /// Delete action method
- ///
- ///
- [HttpDelete("{id}")]
- public void Delete(int id)
- {
- }
- }
打開 xml 注解
值得注意的是:Swagger 默認并不會顯示 XML 注解,需要手工打開它,那怎么做呢?右鍵 Project,選擇 Properties 后切換到 Build 頁面,然后選中 XML documentation file 項 并且指定好 xml 生成的位置,參考如下:
接下來還要在 ConfigureServices 方法下將生成xml 的路徑配置到 swagger 中,如下代碼所示:
- c.IncludeXmlComments(@"D:\Projects\IDG\IDGSwaggerDemo\IDGSwaggerDemo\IDGSwaggerDemo.xml");
這就是打開 Swagger 中的 xml 注解 所需的所有事情。
指定啟動url 到 Swagger UI
要想將啟動項目的url指到 SwaggerUI,右鍵 Project 并選擇 Properties,在 Debug 的 Lanuch browser 上指定 swagger 即可,如下圖所示:
再次運行程序可以發(fā)現(xiàn)默認頁就是 Swagger URL 了,如下圖所示:
從圖中可以看到,5個API方法后面都有相應的 xml 注解了。
Swashbuckle 是一個非常好的工具,可以簡單粗暴的給 API接口生成文檔,從文中也可以看出 Swashbuckle 的配置非常簡單,Swagger 還有一些更高級的功能,比如通過 CSS 來定制 Swagger UI,還可以根據(jù)API的版本生成不同的 Swagger 文檔,后續(xù)的文章還會跟大家介紹更多高級的功能。
譯文鏈接:https://www.infoworld.com/article/3400084/how-to-use-swagger-in-aspnet-core.html
分享題目:如何在ASP.NetCore中使用Swagger
轉載來于:http://www.5511xx.com/article/cceijcs.html


咨詢
建站咨詢
