1+ // Copyright (c) .NET Foundation. All rights reserved.
2+ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
3+
4+ using System ;
5+ using System . Threading . Tasks ;
6+ using Microsoft . AspNetCore . Http ;
7+ using Microsoft . AspNetCore . Routing ;
8+ using Microsoft . Extensions . Internal ;
9+
10+ namespace Microsoft . AspNetCore . Localization . Routing
11+ {
12+ /// <summary>
13+ /// Determines the culture information for a request via values in the route data.
14+ /// </summary>
15+ public class RouteDataRequestCultureProvider : RequestCultureProvider
16+ {
17+ /// <summary>
18+ /// The key that contains the culture name.
19+ /// Defaults to "culture".
20+ /// </summary>
21+ public string RouteDataStringKey { get ; set ; } = "culture" ;
22+
23+ /// <summary>
24+ /// The key that contains the UI culture name. If not specified or no value is found,
25+ /// <see cref="RouteDataStringKey"/> will be used.
26+ /// Defaults to "ui-culture".
27+ /// </summary>
28+ public string UIRouteDataStringKey { get ; set ; } = "ui-culture" ;
29+
30+ /// <inheritdoc />
31+ public override Task < ProviderCultureResult > DetermineProviderCultureResult ( HttpContext httpContext )
32+ {
33+ if ( httpContext == null )
34+ {
35+ throw new ArgumentNullException ( nameof ( httpContext ) ) ;
36+ }
37+
38+ string culture = null ;
39+ string uiCulture = null ;
40+
41+ if ( ! string . IsNullOrEmpty ( RouteDataStringKey ) )
42+ {
43+ culture = httpContext . GetRouteValue ( RouteDataStringKey ) ? . ToString ( ) ;
44+ }
45+
46+ if ( ! string . IsNullOrEmpty ( UIRouteDataStringKey ) )
47+ {
48+ uiCulture = httpContext . GetRouteValue ( UIRouteDataStringKey ) ? . ToString ( ) ;
49+ }
50+
51+ if ( culture == null && uiCulture == null )
52+ {
53+ // No values specified for either so no match
54+ return TaskCache < ProviderCultureResult > . DefaultCompletedTask ;
55+ }
56+
57+ if ( culture != null && uiCulture == null )
58+ {
59+ // Value for culture but not for UI culture so default to culture value for both
60+ uiCulture = culture ;
61+ }
62+
63+ if ( culture == null && uiCulture != null )
64+ {
65+ // Value for UI culture but not for culture so default to UI culture value for both
66+ culture = uiCulture ;
67+ }
68+
69+ var providerResultCulture = new ProviderCultureResult ( culture , uiCulture ) ;
70+
71+ return Task . FromResult ( providerResultCulture ) ;
72+ }
73+ }
74+ }
0 commit comments