1+ // MADE Apps licenses this file to you under the MIT license.
2+ // See the LICENSE file in the project root for more information.
3+
4+ #if NET5_0
5+ namespace MADE . Web . Extensions
6+ {
7+ using Microsoft . AspNetCore . Mvc ;
8+ using Microsoft . AspNetCore . Mvc . Versioning ;
9+ using Microsoft . Extensions . DependencyInjection ;
10+
11+ /// <summary>
12+ /// Defines a collection of extensions for API versioning.
13+ /// </summary>
14+ public static class ApiVersioningExtensions
15+ {
16+ /// <summary>
17+ /// Adds request API versioning for controllers and APIs to the specified services collection.
18+ /// </summary>
19+ /// <param name="services">The <see cref="IServiceCollection">services</see> available in the application.</param>
20+ /// <param name="defaultMajor">The default major version of the API. Default, 1.</param>
21+ /// <param name="defaultMinor">The default minor version of the API. Default, 0.</param>
22+ /// <returns>The configured <paramref name="services"/> object.</returns>
23+ public static IServiceCollection AddApiVersionSupport ( this IServiceCollection services , int defaultMajor = 1 , int defaultMinor = 0 )
24+ {
25+ services . AddVersionedApiExplorer ( options => options . GroupNameFormat = "'v'VVV" ) ;
26+
27+ services . AddApiVersioning ( options =>
28+ {
29+ options . DefaultApiVersion = new ApiVersion ( defaultMajor , defaultMinor ) ;
30+ options . AssumeDefaultVersionWhenUnspecified = true ;
31+ options . ReportApiVersions = true ;
32+ } ) ;
33+
34+ return services ;
35+ }
36+
37+ /// <summary>
38+ /// Adds request header API versioning for controllers and APIs to the specified services collection.
39+ /// </summary>
40+ /// <param name="services">The <see cref="IServiceCollection">services</see> available in the application.</param>
41+ /// <param name="apiHeaderName">The name of the header that is required when making requests to API endpoints. Default, x-api-version.</param>
42+ /// <param name="defaultMajor">The default major version of the API. Default, 1.</param>
43+ /// <param name="defaultMinor">The default minor version of the API. Default, 0.</param>
44+ /// <returns>The configured <paramref name="services"/> object.</returns>
45+ public static IServiceCollection AddApiVersionHeaderSupport ( this IServiceCollection services , string apiHeaderName = "x-api-version" , int defaultMajor = 1 , int defaultMinor = 0 )
46+ {
47+ services . AddVersionedApiExplorer ( options => options . GroupNameFormat = "'v'VVV" ) ;
48+
49+ services . AddApiVersioning ( options =>
50+ {
51+ options . DefaultApiVersion = new ApiVersion ( defaultMajor , defaultMinor ) ;
52+ options . AssumeDefaultVersionWhenUnspecified = true ;
53+ options . ReportApiVersions = true ;
54+ options . ApiVersionReader = new HeaderApiVersionReader ( apiHeaderName ) ;
55+ } ) ;
56+
57+ return services ;
58+ }
59+ }
60+ }
61+ #endif
0 commit comments