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


系列目錄

循序漸進學.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 = "seabluescn@163.com", 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的調試了。 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM