1+ // Copyright (c) .NET Foundation and contributors. All rights reserved.
2+
3+ namespace Microsoft . AspNetCore . Builder ;
4+
5+ using Asp . Versioning ;
6+ using Asp . Versioning . ApiExplorer ;
7+ using Microsoft . AspNetCore . Routing ;
8+ using Microsoft . Extensions . DependencyInjection ;
9+ using Microsoft . Extensions . Options ;
10+
11+ /// <summary>
12+ /// Provides extension methods for <see cref="IEndpointRouteBuilder"/>.
13+ /// </summary>
14+ [ CLSCompliant ( false ) ]
15+ public static class IEndpointRouteBuilderExtensions
16+ {
17+ /// <summary>
18+ /// Returns a read-only list of API version descriptions.
19+ /// </summary>
20+ /// <param name="endpoints">The <see cref="IEndpointRouteBuilder">endpoints</see> to build the
21+ /// API version descriptions from.</param>
22+ /// <returns>A new <see cref="IReadOnlyList{T}">read-only list</see> of<see cref="ApiVersionDescription">API version descriptions</see>.</returns>
23+ public static IReadOnlyList < ApiVersionDescription > DescribeApiVersions ( this IEndpointRouteBuilder endpoints )
24+ {
25+ if ( endpoints == null )
26+ {
27+ throw new ArgumentNullException ( nameof ( endpoints ) ) ;
28+ }
29+
30+ // this should be produced by IApiVersionDescriptionProvider via di; however, for minimal apis, the
31+ // endpoints in the registered EndpointDataSource may not have been built yet. this is important
32+ // for the api explorer extensions (ex: openapi). the following is the same setup that would occur
33+ // through via di, but the IEndpointRouteBuilder is expected to be the WebApplication used during
34+ // setup. unfortunately, the behavior cannot simply be changed by replacing IApiVersionDescriptionProvider
35+ // in the container for minimal apis, but that is not a common scenario. all the types and pieces
36+ // necessary to change this behavior is still possible outside of this method, but it's on the developer
37+ var source = new CompositeEndpointDataSource ( endpoints . DataSources ) ;
38+ var policyManager = endpoints . ServiceProvider . GetRequiredService < ISunsetPolicyManager > ( ) ;
39+ var options = endpoints . ServiceProvider . GetRequiredService < IOptions < ApiExplorerOptions > > ( ) ;
40+ var provider = new DefaultApiVersionDescriptionProvider ( source , policyManager , options ) ;
41+
42+ return provider . ApiVersionDescriptions ;
43+ }
44+ }
0 commit comments