SwaggerExtensions.cs 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. using System.Reflection;
  2. using System.Text;
  3. using Abp.Extensions;
  4. using Microsoft.AspNetCore.Builder;
  5. using Microsoft.AspNetCore.Hosting;
  6. using Microsoft.Extensions.Configuration;
  7. using Microsoft.Extensions.DependencyInjection;
  8. using Microsoft.OpenApi.Models;
  9. using Swashbuckle.AspNetCore.SwaggerUI;
  10. using VberZero.Configuration;
  11. namespace VberAdmin.Swagger
  12. {
  13. public static class SwaggerExtensions
  14. {
  15. private static string _apiVersion = "v1";
  16. /// <summary>
  17. /// 将 ABP 基础 URI 注入 index.html 页面
  18. /// </summary>
  19. /// <param name="options"></param>
  20. /// <param name="pathBase">base path (URL) to application API</param>
  21. public static void InjectBaseUrl(this SwaggerUIOptions options, string pathBase)
  22. {
  23. pathBase = pathBase.EnsureEndsWith('/');
  24. options.HeadContent = new StringBuilder(options.HeadContent)
  25. .AppendLine($"<script> var abp = abp || {{}}; abp.appPath = abp.appPath || '{pathBase}'; </script>")
  26. .ToString();
  27. }
  28. /// <summary>
  29. /// 在 Configure 方法中启用此行和相关行以启用 swagger UI
  30. /// </summary>
  31. /// <param name="services"></param>
  32. /// <param name="env"></param>
  33. public static void ConfigureSwagger(this IServiceCollection services, IWebHostEnvironment env)
  34. {
  35. var appConfiguration = env.GetAppConfiguration();
  36. services.AddSwaggerGen(options =>
  37. {
  38. options.SwaggerDoc(_apiVersion, new OpenApiInfo
  39. {
  40. Version = _apiVersion,
  41. Title = "VberAdmin API",
  42. Description = "VberAdmin",
  43. // uncomment if needed TermsOfService = new Uri("https://example.com/terms"),
  44. //Contact = new OpenApiContact
  45. //{
  46. // Name = "VberAdmin",
  47. // Email = string.Empty,
  48. // Url = new Uri("https://twitter.com/aspboilerplate"),
  49. //},
  50. //License = new OpenApiLicense
  51. //{
  52. // Name = "MIT License",
  53. // Url = new Uri("https://github.com/aspnetboilerplate/aspnetboilerplate/blob/dev/LICENSE"),
  54. //}
  55. });
  56. options.DocInclusionPredicate((docName, description) => true);
  57. // 定义正在使用的 BearerAuth 方案
  58. options.AddSecurityDefinition("bearerAuth", new OpenApiSecurityScheme()
  59. {
  60. Description =
  61. "使用 Bearer 方案的 JWT 授权标头。 例子: \"Authorization: Bearer {token}\"",
  62. Name = "Authorization",
  63. In = ParameterLocation.Header,
  64. Type = SecuritySchemeType.ApiKey
  65. });
  66. options.AddSecurityRequirement(new OpenApiSecurityRequirement
  67. {
  68. {
  69. new OpenApiSecurityScheme
  70. {
  71. Reference = new OpenApiReference {
  72. Type = ReferenceType.SecurityScheme,
  73. Id = "bearerAuth"
  74. }
  75. },
  76. new string[] { }
  77. }
  78. });
  79. //添加摘要
  80. bool canShowSummaries = appConfiguration.GetValue<bool>("Swagger:ShowSummaries");
  81. if (canShowSummaries)
  82. {
  83. var hostXmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
  84. var hostXmlPath = Path.Combine(env.ContentRootPath, hostXmlFile);
  85. options.IncludeXmlComments(hostXmlPath);
  86. var applicationXml = $"VberAdmin.Application.xml";
  87. var applicationXmlPath = Path.Combine(env.ContentRootPath, applicationXml);
  88. options.IncludeXmlComments(applicationXmlPath);
  89. var webCoreXmlFile = $"VberAdmin.Web.Core.xml";
  90. var webCoreXmlPath = Path.Combine(env.ContentRootPath, webCoreXmlFile);
  91. options.IncludeXmlComments(webCoreXmlPath);
  92. }
  93. options.ParameterFilter<SwaggerEnumParameterFilter>();
  94. options.SchemaFilter<SwaggerEnumSchemaFilter>();
  95. options.OperationFilter<SwaggerOperationIdFilter>();
  96. options.OperationFilter<SwaggerOperationFilter>();
  97. options.DocumentFilter<CustomDocFilter>();
  98. });
  99. }
  100. public static void Use_SwaggerUI(this IApplicationBuilder app, Assembly assembly, string namespaceStr = "VberAdmin.Web.Mvc")
  101. {
  102. //启用中间件以将生成的 Swagger 作为 JSON 端点提供服务
  103. app.UseSwagger(c => { c.RouteTemplate = "doc/{documentName}/api.json"; });
  104. // 启用中间件以提供 swagger-ui 资产(HTML、JS、CSS 等)
  105. app.UseSwaggerUI(options =>
  106. {
  107. options.DocumentTitle = "API-系统管理平台";
  108. options.DocExpansion(DocExpansion.None);//设置为none可折叠所有方法
  109. options.DefaultModelsExpandDepth(-1); //设置为 -1 可不显示models
  110. options.RoutePrefix = "doc";//配置后,你的最终访问路径就就是 /doc/index.html 否则 /swagger;
  111. options.SwaggerEndpoint($"/doc/{_apiVersion}/api.json", $"VberAdmin API {_apiVersion}");
  112. options.IndexStream = () => assembly.GetManifestResourceStream($"{namespaceStr}.wwwroot.swagger.ui.index.html");
  113. options.DisplayRequestDuration(); // Controls the display of the request duration (in milliseconds) for "Try it out" requests.
  114. }); // URL: /doc
  115. }
  116. }
  117. }