public override void ConfigureServices(IServiceCollection services) { base.ConfigureServices(services); services.AddSingleton <ApiDocInfoRegistry>(); using (var scope = services.BuildServiceProvider().CreateScope()) { ApiDocInfoRegistry apiDocInfoRegistry = scope.ServiceProvider.GetRequiredService <ApiDocInfoRegistry>(); //AddApiDoc在注册阶段要求Build,以获取所有的文档提供者信息 services.AddApiDoc(apiDocInfoRegistry); } }
internal static IApplicationBuilder UseApiDoc(this IApplicationBuilder app, ApiDocInfoRegistry registry) { app.UseSwagger(); app.UseSwaggerUI(c => { ////serve the Swagger UI at the root (http://localhost:<port>/) //c.RoutePrefix = string.Empty; //switch "~/swagger/index.html" to "~/SwaggerHide/index.html", so now we use the only mvc "~/ApiDoc" entry c.RoutePrefix = "SwaggerHide"; foreach (var apiDocInfo in registry.ApiDocInfos) { c.SwaggerEndpoint(apiDocInfo.Endpoint, apiDocInfo.Name); } }); return(app); }
internal static IServiceCollection AddApiDoc(this IServiceCollection services, ApiDocInfoRegistry registry) { var baseDirectory = AppDomain.CurrentDomain.BaseDirectory ?? string.Empty; services.AddSwaggerGen(setupAction => { var sp = services.BuildServiceProvider(); using (var scope = sp.CreateScope()) { var apiDocInfos = registry.ApiDocInfos; //load xml comments var xmlFiles = apiDocInfos.Select(x => x.XmlFile).Distinct(StringComparer.OrdinalIgnoreCase).ToList(); foreach (var xmlFile in xmlFiles) { var xmlFilePath = Path.Combine(baseDirectory, xmlFile); if (File.Exists(xmlFilePath)) { setupAction.IncludeXmlComments(xmlFilePath); } } //load groups foreach (var apiDocInfo in apiDocInfos) { setupAction.SwaggerDoc(apiDocInfo.Name, new OpenApiInfo() { Title = apiDocInfo.Title, Version = apiDocInfo.Version, Description = apiDocInfo.Description }); } } }); return(services); }