循序漸進學.Net Core Web Api開發系列【2】:利用Swagger調試WebApi

來源:互聯網
上載者:User

標籤:技術   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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.