項目之前開發完接口后,我們還需要寫接口說明文檔,現在有了swagger方便了很多,可以網頁版直接測試,當然了也減少了我們的工作量。
使用swagger生成接口說明文檔,大致需要2個步驟
1、從“管理 NuGet 程序包”對話框中:
-
- 右鍵單擊“解決方案資源管理器” > “管理 NuGet 包”中的項目
- 將“包源”設置為“nuget.org”
- 在搜索框中輸入“Swashbuckle.AspNetCore”
- 從“瀏覽”選項卡中選擇“Swashbuckle.AspNetCore”包,然后單擊“安裝”
2、添加並配置 Swagger 中間件
public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" }); }); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } //啟用靜態文件中間件 app.UseStaticFiles(); // Enable middleware to serve generated Swagger as a JSON endpoint. app.UseSwagger(); // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), // specifying the Swagger JSON endpoint. app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); }); app.UseHttpsRedirection(); app.UseMvc(); }
經過上面的2步,我們的接口說明文檔就生成好啦,運行項目,輸入https://localhost:**/swagger/index.html地址,效果如下: 細心的童鞋可能發現,沒有接口說明注釋,我們稍做修改就可以顯示注釋,步驟如下:
services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" }); var xmlPath = Path.Combine(AppContext.BaseDirectory, "OfficalProject.xml"); c.IncludeXmlComments(xmlPath); }); //啟用靜態文件中間件 app.UseStaticFiles(); // Enable middleware to serve generated Swagger as a JSON endpoint. app.UseSwagger(c => { c.RouteTemplate = "swagger/{documentName}/swagger.json"; }); // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), // specifying the Swagger JSON endpoint. app.UseSwaggerUI(c => { // c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); c.SwaggerEndpoint("v1/swagger.json", "SwaggerTest"); //c.SwaggerEndpoint("/swagger/v2/swagger.json", "My API V2"); });
上面紅色字體的就是修改的部分,下面我們的文檔就有注釋啦
重要! 重要! 重要!
我們如在實際使用中,如遇到接口文檔不能正常顯示問題,可以調用這個地址進行排錯https://localhost:***/swagger/v1/swagger.json
實際應用中,某些接口我們想不在外面顯示,只需在控制器上面加上 [ApiExplorerSettings(IgnoreApi =true)]
[ApiExplorerSettings(IgnoreApi =true)] //設置該控制器不在swagger文檔中顯示 [Route("api/[controller]")] [ApiController] public class ValuesController : ControllerBase { // GET api/values [HttpGet] public ActionResult<IEnumerable<string>> Get() { return new string[] { "value1", "value2" }; } }