2019年5月18日 星期六

ASP.NET Core 安裝 Swashbuckle 自動產生 API 說明文件檔案

目的:自動抓取註解產生下面的 API 說明文件網頁



























NuGet 安裝 Swashbuckle.AspNetCore


引用 Swashbuckle.AspNetCore.Swagger

  1. using Swashbuckle.AspNetCore.Swagger;
設定 Startup.cs 的 ConfigureServices
  1. public void ConfigureServices(IServiceCollection services)
  2. {
  3. services.AddMvc();
  4. #region 註冊 Swagger
  5. // 註冊 Swagger
  6. services.AddSwaggerGen(c =>
  7. {
  8. c.SwaggerDoc(
  9. // name: 攸關 SwaggerDocument 的 URL 位置。
  10. name: "v1",
  11. // info: 是用於 SwaggerDocument 版本資訊的顯示(內容非必填)。
  12. info: new Info
  13. {
  14. Title = "標題",
  15. Version = "版本號 1.0.0",
  16. Description = "說明",
  17. TermsOfService = "無",
  18. Contact = new Contact
  19. {
  20. Name = "強尼 John Wu",
  21. Url = "https://blog.johnwu.cc"
  22. },
  23. License = new License
  24. {
  25. Name = "西西 CC BY-NC-SA 4.0",
  26. Url = "https://creativecommons.org/licenses/by-nc-sa/4.0/"
  27. }
  28. }
  29. );
  30. // 為 Swagger JSON and UI設置xml文檔註釋路徑
  31. var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location);//獲取應用程序所在目錄(絕對,不受工作目錄影響,建議採用此方法獲取路徑)
  32. var xmlPath = Path.Combine(basePath, "Swagger.xml");
  33. c.IncludeXmlComments(xmlPath);
  34. });
  35. #endregion 註冊 Swagger
  36. }


點選「屬性」「建置」
新增「隱藏警告」1591
新增「XML 文件檔案」程式碼設定 Swagger.xml 這邊也填入 Swagger.xml



















設定 Startup.cs 的 Configure
  1. public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  2. {
  3. #region 註冊 Swagger
  4. // 註冊 Swagger
  5. app.UseSwagger();
  6. app.UseSwaggerUI(c =>
  7. {
  8. c.SwaggerEndpoint(
  9. // url: 需配合 SwaggerDoc 的 name。 "/swagger/{SwaggerDoc name}/swagger.json"
  10. url: "/swagger/v1/swagger.json",
  11. // name: 用於 Swagger UI 右上角選擇不同版本的 SwaggerDocument 顯示名稱使用。
  12. name: "RESTful API v1.0.0"
  13. );
  14. });
  15. #endregion 註冊 Swagger
  16. app.UseMvc(routes =>
  17. {
  18. routes.MapRoute(name: "default", template: "{controller}/{action}/{id?}");
  19. });
  20. }
程式開啟後,輸入網址 http://localhost:port/swagger
就能開啟 Swagger UI 網頁

























PS.在 Blazor 安裝 Swagger 後,
在 Ubuntu 上執行有異常(收不到封包),
最後換了 NSwag 才正常










沒有留言:

Visual Studio 2017/2019 推薦的擴充功能與更新

參考文章: 覺得 Google 的 Blogger 不太順手?透過 HTML 的 iframe 移花接木 HackMD