[英].NET Core MVC localization set culture in library
我很沮丧,我尝试使用标准的Microsoft本地化机制。 但是,从现在开始的两天以来,我努力达到可以在外部库中设置/更改当前文化的目的。
但是系统会忽略它。 ;(
这是我的StartUp.cs
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); //TODO: With .net Core 2.1 services.AddHttpContextAccessor();
services.AddMvc()
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
.AddDataAnnotationsLocalization();
services.AddPortableObjectLocalization(options => options.ResourcesPath = "Localization");
services.Replace(ServiceDescriptor.Singleton<ILocalizationFileLocationProvider, LocalizationLoader>());
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
var supportedCultures = new[]
{
new CultureInfo("de-DE"),
new CultureInfo("en-GB"),
};
app.UseRequestLocalization(new RequestLocalizationOptions
{
DefaultRequestCulture = new RequestCulture("de-DE"),
// Formatting numbers, dates, etc.
SupportedCultures = supportedCultures,
// UI strings that we have localized.
SupportedUICultures = supportedCultures
});
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.Routes.Add((IRouter) dynamicRouter);
});
}
这是我的控制器操作,它在库中(可能不重要,而不是直接在MVC应用程序中)。 该操作将被调用,不会引发任何异常,但是在IViewLocalizer中,区域性始终始终是“ de-DE”。
public async Task<IActionResult> Get(string contentItemId)
{
// Just a try from the Internet
_httpContextAccessor.HttpContext.Response.Cookies.Append(
CookieRequestCultureProvider.DefaultCookieName,
CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(new CultureInfo("en-GB"))),
new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) }
);
// I thought one of these are right
CultureInfo.CurrentCulture = new CultureInfo("en-GB");
CultureInfo.CurrentUICulture = new CultureInfo("en-GB");
CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("en-GB");
CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo("en-GB");
return View();
}
总是在我再次执行操作(刷新F5浏览器)时,CultureInfo再次为“ de-DE”(默认)。 ;(
尝试像这样在服务中添加您的配置:
services.Configure<RequestLocalizationOptions>(options =>
{
var supportedCultures = new[]
{
new CultureInfo("en-US"),
new CultureInfo("fr-FR")
};
options.DefaultRequestCulture = new RequestCulture(culture: "en-US", uiCulture: "en-US");
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
});
然后让UseRequestLocalization
空:
app.UseRequestLocalization();
点击下一个链接以完成启动:
希望这个帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.