1. 程式人生 > >循序漸進學.Net Core Web Api開發系列【2】:利用Swagger除錯WebApi

循序漸進學.Net Core Web Api開發系列【2】:利用Swagger除錯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的除錯了。