標籤:技術 asp class 技術分享 express new orm ext des
系列目錄
循序漸進學.Net Core Web Api開發系列目錄
本系列涉及到的源碼:https://github.com/seabluescn/Blog_WebApi
一、概述
既然前後端開發完全分離,那麼介面的測試和文檔就顯得非常重要,文檔維護是一件比較麻煩的事情,特別是變更的文檔,這時採用Swagger就會非常方便,同時解決了測試和介面文檔兩個問題。
二、使用NuGet擷取包
使用NuGet搜尋包:Swashbuckle.aspnetcore並安裝。
三、添加代碼
在Startup類的ConfigureServices方法內添加下面代碼(加粗部分)
public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddSwaggerGen(option => { option.SwaggerDoc("v1", new Info { Version = "v1", Title = "SaleService介面文檔", Description = "RESTful API for SaleService.", TermsOfService = "None", Contact = new Contact { Name = "seabluescn", Email = "[email protected]", Url = "" } }); //Set the comments path for the swagger json and ui. var basePath = PlatformServices.Default.Application.ApplicationBasePath; var xmlPath = Path.Combine(basePath, "SaleService.xml"); option.IncludeXmlComments(xmlPath); }); }
在Startup類的Configure方法內添加下面代碼(加粗部分)
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseMvcWithDefaultRoute(); app.UseSwagger(); app.UseSwaggerUI(option => { option.ShowExtensions(); option.SwaggerEndpoint("/swagger/v1/swagger.json", "SaleService V1"); }); }
四、配置
需要在組建組態選項內勾選XML文檔檔案,項目編譯時間會產生該檔案。Debug和Release模式都設定一下。否則會報一個System.IO.FileNotFoundException的錯誤。
五、啟動
啟動項目,瀏覽器輸入:http://localhost:50793/swagger/ 即可。
也可以修改launchsettings.json檔案,預設項目啟動時運行swagger
{ "iisSettings": { "windowsAuthentication": false, "anonymousAuthentication": true, "iisExpress": { "applicationUrl": "http://localhost:50792/", "sslPort": 0 } }, "profiles": { "IIS Express": { "commandName": "IISExpress", "launchBrowser": true, "launchUrl": "api/values", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } }, "SaleService": { "commandName": "Project", "launchBrowser": true, "launchUrl": "swagger", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" }, "applicationUrl": "http://localhost:50793/" } }}
如果你對你的控制器方法進行了注釋,swagger介面頁面就會體現出來。
/// <summary> /// 根據產品編號查詢產品資訊 /// </summary> /// <param name="code">產品編碼</param> /// <returns>產品資訊</returns> [HttpGet("{code}")] public Product GetProduct(String code) { var product = new Product { ProductCode = code, ProductName = "啫喱水" }; return product; }
下面為Swagger的首頁:可以用它進行API的調試了。
循序漸進學.Net Core Web Api開發系列【2】:利用Swagger調試WebApi