【发布时间】:2021-11-06 21:30:47
【问题描述】:
我必须在我的网络应用程序中添加本地化。
请求是 grpc 服务将为所有用户提供默认语言,因此在启动时我试图读取该值但不知道如何在 new CustomRequestCultureProvider 中使用已注册的服务
public static CultureInfo[] supportedCultures = new[] { new CultureInfo("it-IT"), new CultureInfo("en-US")};
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<ISpaClient, GrpcSpaClient>();
services.AddLocalization(options => options.ResourcesPath = "Resources");
services.AddMvc()
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
.AddDataAnnotationsLocalization();
services.Configure<RequestLocalizationOptions>(options =>
{
options.DefaultRequestCulture = new RequestCulture(culture: supportedCultures[0].ToString(), uiCulture: supportedCultures[0].ToString());
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
options.RequestCultureProviders.Clear();
options.RequestCultureProviders.Add(new MyCustomRequestCultureProvider());
});
}
我的自定义类
public class MyCustomRequestCultureProvider : RequestCultureProvider
{
public override async Task<ProviderCultureResult> DetermineProviderCultureResult(HttpContext httpContext)
{
await Task.Yield();
if (httpContext == null)
{
throw new ArgumentNullException(nameof(httpContext));
}
if (!httpContext.User.Identity.IsAuthenticated)
{
return null;
}
var culture = httpContext.User
.Claims
.FirstOrDefault(c => c.Type == TipoClaim.linguaPredefinita.ToString())?
.Value;
if (culture == null)
{
return null;
}
return new ProviderCultureResult(culture);
}
}
但是这里httpContext.User 永远不是Authenticated,即使页面是
【问题讨论】:
标签: .net localization asp.net-core-mvc claims-based-identity