1. 程式人生 > >在.net core web api專案中安裝swagger展示api介面(相當於生成api文件)

在.net core web api專案中安裝swagger展示api介面(相當於生成api文件)

1,  建立或開啟專案後,在“程式包管理器控制檯”中執行以下命令新增包引用:

Install-Package Swashbuckle.AspNetCore

 

2,在專案中開啟Startup.cs檔案,找到 Configure 方法,在其中新增如下程式碼:

 app.UseSwagger();

 app.UseSwaggerUI(c =>

 {

     c.SwaggerEndpoint("/swagger/v1/swagger.json", "MsSystem API V1");

 });

 

附新增後代碼截圖如下:

 

 

 

2, 繼續在Startup.cs檔案中, 找到 ConfigureServices方法,在其中新增如下程式碼:

services.AddSwaggerGen();

services.ConfigureSwaggerGen(options =>

{

    options.SwaggerDoc("v1", new Info {Version = "v1",Title = "MsSystem API"});

    //該檔案路徑為專案---"屬性"---"生成"---"輸出"---"xml文件檔案"的路徑

string xmlFile= @"C:\Users\Administrator\source\repos\WebApiSwaggerDemo\

WebApiSwaggerDemo\WebApiSwaggerDemo.xml";

    options.IncludeXmlComments(xmlFile);

    options.DescribeAllEnumsAsStrings();

});

 

注意:

1,  程式碼new Info處可能會報錯,增加using Swashbuckle.AspNetCore.Swagger;引用即可。

2,  xmlFile檔案的路徑為當前專案屬性 "生成"---"輸出"---"xml文件檔案"的路徑,需勾選此項才能獲得(如下圖所示):

 

 

 附xml檔案路徑獲取截圖如下:

  

3,修改Properties下的launchSettings.json配置檔案,指定profiles---IIS Express---launchUrl值為swagger。如下圖所示: 

 

5:按F5啟動專案。展示的是預設首頁(如圖1所示)。在瀏覽器位址列加上swagger按回車即可看到API描述(如圖2所示)。

 

圖1

 

 圖2

 

 

注意:

在生成的Swagger文件中如果要包含API介面註釋資訊,需在專案生成屬性中勾選輸出xml文件檔案,並且在專案的Startup.cs檔案中通過services.ConfigureSwaggerGen函式指明輸出的xml文件檔案路徑。可按下述步驟進行檢查。

 

操作步驟:

1、  選中專案名稱,右擊後在快捷選單中選“屬性”,開啟專案屬性對話方塊(如下圖所示)

 

 

2、  在專案屬性對話方塊中左邊選“生成”,右邊勾選“輸出”下的“xml文件檔案”,然後記住生成的xml檔案路徑

本示例xml檔案路徑為“D:\STUDY\SwaggerDemo\SwaggerDemo\SwaggerDemo.xml”,推薦直接複製此路徑。

 

   

3、  開啟專案Startup.cs檔案,通過編寫services.ConfigureSwaggerGen函式指明輸出的xml文件檔案路徑(如下圖所示)

 

 

附示例程式碼如下:

public void ConfigureServices(IServiceCollection services)

{

  services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

  services.AddSwaggerGen();

  services.ConfigureSwaggerGen(options =>

  {

      options.SwaggerDoc("v1", new Info { Version = "v1", Title = "MsSystem API" });

      //該檔案路徑為專案屬性中"生成"---"輸出"---"xml文件檔案"的路徑

      string xmlFile = @"D:\STUDY\SwaggerDemo\SwaggerDemo\SwaggerDemo.xml";

      options.IncludeXmlComments(xmlFile);

      options.DescribeAllEnumsAsStrings();

});

}