|
| 1 | +using Microsoft.AspNetCore.Http; |
| 2 | +using Microsoft.AspNetCore.Localization; |
| 3 | +using System.Collections.Generic; |
| 4 | +using System.Globalization; |
| 5 | +using System.Linq; |
| 6 | +using System.Threading.Tasks; |
| 7 | + |
| 8 | +namespace cloudscribe.Web.Localization |
| 9 | +{ |
| 10 | + public class FirstUrlSegmentRequestCultureProvider : RequestCultureProvider |
| 11 | + { |
| 12 | + public FirstUrlSegmentRequestCultureProvider( |
| 13 | + IList<CultureInfo> supportedUICultures, |
| 14 | + IList<CultureInfo> supportedCultures = null |
| 15 | + ) |
| 16 | + { |
| 17 | + _supportedUICultures = supportedUICultures; |
| 18 | + _supportedCultures = supportedCultures; |
| 19 | + } |
| 20 | + |
| 21 | + private readonly IList<CultureInfo> _supportedUICultures; |
| 22 | + private readonly IList<CultureInfo> _supportedCultures; |
| 23 | + |
| 24 | + public override Task<ProviderCultureResult> DetermineProviderCultureResult(HttpContext httpContext) |
| 25 | + { |
| 26 | + var pathStartingSegment = GetStartingSegment(httpContext.Request.Path); |
| 27 | + |
| 28 | + if (!string.IsNullOrWhiteSpace(pathStartingSegment)) |
| 29 | + { |
| 30 | + var matchingUICulture = _supportedUICultures.Where(x => x.Name == pathStartingSegment || x.TwoLetterISOLanguageName == pathStartingSegment).FirstOrDefault(); |
| 31 | + CultureInfo mainCulture = null; |
| 32 | + if (_supportedCultures != null) |
| 33 | + { |
| 34 | + mainCulture = _supportedCultures.Where(x => x.Name == pathStartingSegment || x.TwoLetterISOLanguageName == pathStartingSegment).FirstOrDefault(); |
| 35 | + } |
| 36 | + if (matchingUICulture != null) |
| 37 | + { |
| 38 | + if (mainCulture != null) |
| 39 | + { |
| 40 | + return Task.FromResult(new ProviderCultureResult(mainCulture.Name, matchingUICulture.Name)); |
| 41 | + } |
| 42 | + return Task.FromResult(new ProviderCultureResult(matchingUICulture.Name, matchingUICulture.Name)); |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + //nothing matched |
| 47 | + return NullProviderCultureResult; |
| 48 | + |
| 49 | + } |
| 50 | + |
| 51 | + private string GetStartingSegment(string requestPath) |
| 52 | + { |
| 53 | + if (string.IsNullOrEmpty(requestPath)) return requestPath; |
| 54 | + if (!requestPath.Contains("/")) return requestPath; |
| 55 | + |
| 56 | + var segments = SplitOnCharAndTrim(requestPath, '/'); |
| 57 | + return segments.FirstOrDefault(); |
| 58 | + } |
| 59 | + |
| 60 | + private List<string> SplitOnCharAndTrim(string s, char c) |
| 61 | + { |
| 62 | + List<string> list = new List<string>(); |
| 63 | + if (string.IsNullOrWhiteSpace(s)) { return list; } |
| 64 | + |
| 65 | + string[] a = s.Split(c); |
| 66 | + foreach (string item in a) |
| 67 | + { |
| 68 | + if (!string.IsNullOrWhiteSpace(item)) { list.Add(item.Trim()); } |
| 69 | + } |
| 70 | + |
| 71 | + |
| 72 | + return list; |
| 73 | + } |
| 74 | + } |
| 75 | +} |
0 commit comments