|
| 1 | +#nullable enable |
| 2 | +using System; |
| 3 | +using System.Collections; |
| 4 | +using System.Collections.Generic; |
| 5 | +using System.Linq; |
| 6 | +using System.Threading.Tasks; |
| 7 | +using DotVVM.Framework.Configuration; |
| 8 | +using DotVVM.Framework.Hosting.Middlewares; |
| 9 | +using DotVVM.Framework.Routing; |
| 10 | +using Microsoft.AspNetCore.Http; |
| 11 | +using Microsoft.AspNetCore.Localization; |
| 12 | +using Microsoft.Extensions.DependencyInjection; |
| 13 | + |
| 14 | +namespace DotVVM.Framework.Hosting.AspNetCore.Localization; |
| 15 | + |
| 16 | +public class DotvvmRoutingRequestCultureProvider : IRequestCultureProvider |
| 17 | +{ |
| 18 | + private static readonly object locker = new(); |
| 19 | + private static IReadOnlyList<LocalizedDotvvmRoute>? cachedRoutes; |
| 20 | + |
| 21 | + public Task<ProviderCultureResult?> DetermineProviderCultureResult(HttpContext httpContext) |
| 22 | + { |
| 23 | + EnsureCachedRoutes(httpContext); |
| 24 | + |
| 25 | + // find matching localizable route and extract culture from it |
| 26 | + var url = DotvvmRoutingMiddleware.GetRouteMatchUrl(httpContext.Request.Path.Value!, httpContext.Request.QueryString.Value!); |
| 27 | + foreach (var route in cachedRoutes!) |
| 28 | + { |
| 29 | + if (route.IsPartialMatch(url, out _, out var values, out var matchedCulture)) |
| 30 | + { |
| 31 | + return Task.FromResult<ProviderCultureResult?>(new ProviderCultureResult(matchedCulture)); |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + return Task.FromResult<ProviderCultureResult?>(null); |
| 36 | + } |
| 37 | + |
| 38 | + private void EnsureCachedRoutes(HttpContext httpContext) |
| 39 | + { |
| 40 | + if (cachedRoutes == null) |
| 41 | + { |
| 42 | + lock (locker) |
| 43 | + { |
| 44 | + if (cachedRoutes == null) |
| 45 | + { |
| 46 | + // try to obtain DotVVM configuration |
| 47 | + if (httpContext.RequestServices.GetService<DotvvmConfiguration>() is not { } config) |
| 48 | + { |
| 49 | + throw new InvalidOperationException("DotVVM configuration not found in the service provider."); |
| 50 | + } |
| 51 | + |
| 52 | + // try to obtain DotVVM routes |
| 53 | + cachedRoutes = config.RouteTable |
| 54 | + .OfType<LocalizedDotvvmRoute>() |
| 55 | + .ToArray(); |
| 56 | + } |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | +} |
0 commit comments