按部就班學.Net Core Web Api開發系列【2】:利用Swagger調試WebApi

系列目錄html

按部就班學.Net Core Web Api開發系列目錄git

 本系列涉及到的源碼下載地址:https://github.com/seabluescn/Blog_WebApigithub

 

1、概述json

既然先後端開發徹底分離,那麼接口的測試和文檔就顯得很是重要,文檔維護是一件比較麻煩的事情,特別是變動的文檔,這時採用Swagger就會很是方便,同時解決了測試和接口文檔兩個問題。windows

 

2、使用NuGet獲取包後端

使用NuGet搜索包:Swashbuckle.aspnetcore並安裝。api

 

3、添加代碼瀏覽器

在Startup類的ConfigureServices方法內添加下面代碼(加粗部分)app

      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"); });
        }

 

4、配置

須要在生成配置選項內勾選XML文檔文件,項目編譯時會生成該文件。Debug和Release模式都設置一下。不然會報一個System.IO.FileNotFoundException的錯誤。

 

5、啓動

 啓動項目,瀏覽器輸入: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的調試了。 

相關文章
相關標籤/搜索