【发布时间】:2018-04-17 20:39:38
【问题描述】:
我很沮丧,我尝试使用标准的 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”(默认)。 ;(
【问题讨论】:
-
为什么你甚至使用
_httpContextAccessor.HttpContext而不仅仅是this.HttpContext(或者甚至没有this)?另外,AddPortableObjectLocalization是什么?这不是官方的做法 -
我遇到了类似的问题,我使用 CustomControllerFactory 解决了它,我(在
CreateControllerfunction 中)设置了 CurrentCulture 和 CurrentUICulture并用相同的文化实例化我的库。 -
你可能会发现我的回答here很有用
-
@CamiloTerevinto 我不在那个“控制器”类中使用控制器,我只使用控制器属性。 (出于不同的原因) AddPortableObjectLocalization 是官方的,它不是 resx 文件,它是 .po 文件。 schlonzo:我会看看这个。
标签: c# asp.net-core