Skip to content

Instantly share code, notes, and snippets.

@maliming
Created December 12, 2019 10:01
Show Gist options
  • Select an option

  • Save maliming/23f5c1b431cddfe42bedcf60f9f6b774 to your computer and use it in GitHub Desktop.

Select an option

Save maliming/23f5c1b431cddfe42bedcf60f9f6b774 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.RequestLocalization;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Primitives;
namespace MyCompanyName.MyProjectName.Web
{
public class ChineseRequestCultureProvider : RequestCultureProvider
{
private readonly Dictionary<string, string> _culturesMaps;
private readonly Dictionary<string, string> _uiCulturesMaps;
public ChineseRequestCultureProvider(Dictionary<string, string> culturesMaps, Dictionary<string, string> uiCulturesMaps)
{
_culturesMaps = culturesMaps;
_uiCulturesMaps = uiCulturesMaps;
}
public override async Task<ProviderCultureResult> DetermineProviderCultureResult(HttpContext httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException(nameof(httpContext));
}
var chineseCultures = new List<StringSegment>();
var chineseUiCultures = new List<StringSegment>();
var requestLocalizationOptionsProvider = httpContext.RequestServices.GetRequiredService<IAbpRequestLocalizationOptionsProvider>();
foreach (var provider in requestLocalizationOptionsProvider.GetLocalizationOptions().RequestCultureProviders)
{
if (provider == this)
{
continue;
}
var providerCultureResult = await provider.DetermineProviderCultureResult(httpContext);
if (providerCultureResult == null)
{
continue;
}
var cultures = providerCultureResult.Cultures;
var uiCultures = providerCultureResult.UICultures;
chineseCultures.AddRange(from cultureName in cultures
where cultureName != null && _culturesMaps.ContainsKey(cultureName.Value)
select new StringSegment(_culturesMaps[cultureName.Value]));
chineseUiCultures.AddRange(from cultureName in uiCultures
where cultureName != null && _uiCulturesMaps.ContainsKey(cultureName.Value)
select new StringSegment(_uiCulturesMaps[cultureName.Value]));
}
if (!chineseCultures.Any() || !chineseUiCultures.Any())
{
return await NullProviderCultureResult;
}
return new ProviderCultureResult(chineseCultures, chineseUiCultures);
}
}
}
/*
app.UseAbpRequestLocalization(options =>
{
var maps = new Dictionary<string, string>()
{
{"zh", "zh-Hans"},
{"zh-tw", "zh-Hans"},
{"zh-CN", "zh-Hans"}
};
options.RequestCultureProviders.Insert(0, new ChineseRequestCultureProvider(maps, maps));
});
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment