forked from domaindrivendev/Swashbuckle.AspNetCore
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSwaggerBuilderExtensions.cs
More file actions
77 lines (66 loc) · 2.63 KB
/
SwaggerBuilderExtensions.cs
File metadata and controls
77 lines (66 loc) · 2.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
using System;
#if (!NETSTANDARD2_0)
using System.Linq;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.Routing.Patterns;
using Microsoft.AspNetCore.Routing.Template;
#endif
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Swashbuckle.AspNetCore.Swagger;
namespace Microsoft.AspNetCore.Builder
{
public static class SwaggerBuilderExtensions
{
/// <summary>
/// Register the Swagger middleware with provided options
/// </summary>
public static IApplicationBuilder UseSwagger(this IApplicationBuilder app, SwaggerOptions options)
{
#if (!NETSTANDARD2_0)
return app.UseMiddleware<SwaggerMiddleware>(options, app.ApplicationServices.GetRequiredService<TemplateBinderFactory>());
#else
return app.UseMiddleware<SwaggerMiddleware>(options);
#endif
}
/// <summary>
/// Register the Swagger middleware with optional setup action for DI-injected options
/// </summary>
public static IApplicationBuilder UseSwagger(
this IApplicationBuilder app,
Action<SwaggerOptions> setupAction = null)
{
SwaggerOptions options;
using (var scope = app.ApplicationServices.CreateScope())
{
options = scope.ServiceProvider.GetRequiredService<IOptionsSnapshot<SwaggerOptions>>().Value;
setupAction?.Invoke(options);
}
return app.UseSwagger(options);
}
#if (!NETSTANDARD2_0)
public static IEndpointConventionBuilder MapSwagger(
this IEndpointRouteBuilder endpoints,
string pattern = SwaggerOptions.DefaultRouteTemplate,
Action<SwaggerEndpointOptions> setupAction = null)
{
if (!RoutePatternFactory.Parse(pattern).Parameters.Any(x => x.Name == "documentName"))
{
throw new ArgumentException("Pattern must contain '{documentName}' parameter", nameof(pattern));
}
Action<SwaggerOptions> endpointSetupAction = options =>
{
var endpointOptions = new SwaggerEndpointOptions();
setupAction?.Invoke(endpointOptions);
options.RouteTemplate = pattern;
options.SerializeAsV2 = endpointOptions.SerializeAsV2;
options.PreSerializeFilters.AddRange(endpointOptions.PreSerializeFilters);
};
var pipeline = endpoints.CreateApplicationBuilder()
.UseSwagger(endpointSetupAction)
.Build();
return endpoints.MapGet(pattern, pipeline);
}
#endif
}
}