Swagger的 ASP.NET Core Web API 幫助頁

使用 Web API 時,瞭解其各種方法對開發人員來說可能是一項挑戰。 Swagger 也稱爲OpenAPI,解決了爲 Web API 生成有用文檔和幫助頁的問題。 它具有諸如交互式文檔、客戶端 SDK 生成和 API 可發現性等優點。

Swashbuckle 有三個主要組成部分:

  1. 1.      Swashbuckle.AspNetCore.Swagger:將 SwaggerDocument 對象公開爲 JSON 終結點的 Swagger 對象模型和中間件。

  2. 2.      Swashbuckle.AspNetCore.SwaggerGen:從路由、控制器和模型直接生成 SwaggerDocument 對象的 Swagger 生成器。 它通常與 Swagger 終結點中間件結合,以自動公開 Swagger JSON。

  3. 3.      Swashbuckle.AspNetCore.SwaggerUI:Swagger UI 工具的嵌入式版本。 它解釋 Swagger JSON 以構建描述 Web API 功能的可自定義的豐富體驗。 它包括針對公共方法的內置測試工具。

添加Swashbuckle.AspNetCore的方法

1.從“程序包管理器控制檯”窗口:

·       轉到“視圖” > “其他窗口” > “程序包管理器控制檯”

·       導航到包含.csproj 文件的目錄

·       請執行以下命令:

 

Install-Package Swashbuckle.AspNetCore-Version 5.0.0-rc4

2.從“管理 NuGet 程序包”對話框中:

·       右鍵單擊“解決方案資源管理器” > “管理 NuGet 包”中的項目

·       將“包源”設置爲“nuget.org”

·       確保啓用“包括預發行版”選項

·       在搜索框中輸入“Swashbuckle.AspNetCore”

·       從“瀏覽”選項卡中選擇最新的“Swashbuckle.AspNetCore”包,然後單擊“安裝”

添加並配置 Swagger 中間件

將 Swagger 生成器添加到 Startup.ConfigureServices 方法中的服務集合中:


public void ConfigureServices(IServiceCollection services)
  {
      services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

      services.AddSwaggerGen(c =>
      {
          c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
        
      });
  }

在 Startup.Configure 方法中,啓用中間件爲生成的 JSON 文檔和 Swagger UI 提供服務


public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("./swagger/v1/swagger.json", "My API V1");
                  });
    app.UseMvc();
}

啓動應用,並導航到 http://localhost:<port>/swagger/v1/swagger.json。 生成的描述終結點的文檔顯示在 Swagger 規範 (swagger.json) 中。

可在 http://localhost:<port>/swagger 找到 Swagger UI。 通過 Swagger UI 瀏覽 API,並將其合併其他計劃中。

要在應用的根(http://localhost:<port>/) 處提供 Swagger UI,請將RoutePrefix 屬性設置爲空字符串:

 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  {
      if (env.IsDevelopment())
      {
          app.UseDeveloperExceptionPage();
      }
      app.UseSwagger();
      app.UseSwaggerUI(c =>
      {
          c.SwaggerEndpoint("./swagger/v1/swagger.json", "My API V1");
          c.RoutePrefix = string.Empty;
      });
      app.UseMvc();
  }

並將launchSettings.json文件中的    "launchUrl": "api/values"註釋掉


{
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "iisSettings": {
    "windowsAuthentication": false, 
    "anonymousAuthentication": true, 
    "iisExpress": {
      "applicationUrl": "http://localhost:52655",
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      //"launchUrl": "swagger",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "appDemo": {
      "commandName": "Project",
      "launchBrowser": true,
      //"launchUrl": "swagger",
      "applicationUrl": "http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

自定義和擴展

Swagger 提供了爲對象模型進行歸檔和自定義 UI 以匹配你的主題的選項。

API 信息和說明

傳遞給 AddSwaggerGen 方法的配置操作會添加諸如作者、許可證和說明的信息:

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
 public void ConfigureServices(IServiceCollection services)        {            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddSwaggerGen(c =>            {

                c.SwaggerDoc("v1", new Info                {                    Version = "v1",                    Title = "ToDo API",                    Description = "A simple example ASP.NET Core Web API",                    TermsOfService = "https://blog.csdn.net/zhoubangbang1",                    Contact = new Contact                    {                        Name = "zbb",                        Email = string.Empty,                        Url = "https://blog.csdn.net/zhoubangbang1",                    },                    License = new License                    {                        Name = "Use under LICX",                        Url = "https://blog.csdn.net/zhoubangbang1",                    }                });                          });        }

運行結果:

 

爲接口添加註釋

將 Swagger 配置爲使用按照上述說明生成的 XML 文件。 對於Linux 或非 Windows 操作系統,文件名和路徑區分大小寫。 例如,“TodoApi.XML”文件在 Windows 上有效,但在 CentOS 上無效。

右鍵項目名稱=>屬性=>生成,勾選“輸出”下面的“xml文檔文件”,系統會默認生成一個,當然老規矩,你也可以自己起一個名字:

這裏我用的是相對路徑,可以直接生成到 api 層的 bin文件夾下

 

public void ConfigureServices(IServiceCollection services){    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    services.AddSwaggerGen(c =>    {

        c.SwaggerDoc("v1", new Info        {            Version = "v1",            Title = "ToDo API",            Description = "A simple example ASP.NET Core Web API",            TermsOfService = "https://blog.csdn.net/zhoubangbang1",            Contact = new Contact            {                Name = "zbb",                Email = string.Empty,                Url = "https://blog.csdn.net/zhoubangbang1",            },            License = new License            {                Name = "Use under LICX",                Url = "https://blog.csdn.net/zhoubangbang1",            }        });        //就是這裏
        var basePath = PlatformServices.Default.Application.ApplicationBasePath;        var xmlPath = Path.Combine(basePath, " appDemo.xml");//這個就是剛剛配置的xml文件名        c.IncludeXmlComments(xmlPath, true);//默認的第二個參數是false,這個是controller的註釋,記得修改                                                });}

 

此時,先別忙着運行項目,會出現很多的警告

這是因爲swagger把一些接口方法都通過xml文件配置了。

如果你不想每一個方法都這麼加註釋,可以這麼配置(對當前項目進行配置,可以忽略警告,記得在後邊加上分號 ;1591):

 

最後的運行結果:

 

請關注我的微信公衆號,我們一起進步:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章