我一直在尝试按照microsoft 文档为我的 asp .NET Core 1.0 RTM Web 应用程序实现本地化,但我无法让它工作。我遇到的问题是,无论我如何尝试设置文化,它总是显示来自英语资源文件的字符串。
如果有人有 5 分钟的时间,我将非常感谢您的意见。
这是我关于本地化的 Startup.cs 内容:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddMvc()
.AddViewLocalization(LanguageViewLocationExpanderFormat.SubFolder)
.AddDataAnnotationsLocalization();
services.AddScoped<LocalizationFilter>();
services.AddLocalization(options => options.ResourcesPath = "Resources");
var supportedCultures = new List<CultureInfo>{
new CultureInfo("en-US"),
new CultureInfo("sl-SI"),
new CultureInfo("de-DE"),
new CultureInfo("hr-HR")
};
services.Configure<RequestLocalizationOptions>(options =>
{
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
options.DefaultRequestCulture = new RequestCulture(new CultureInfo("en-US"),
new CultureInfo("en-US"));
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env,
ILoggerFactory loggerFactory)
{
...
var supportedCultures = new List<CultureInfo>{
new CultureInfo("en-US"),
new CultureInfo("sl-SI"),
new CultureInfo("de-DE"),
new CultureInfo("hr-HR")
};
var requestLocalizationOptions = new RequestLocalizationOptions
{
SupportedCultures = supportedCultures,
SupportedUICultures = supportedCultures,
DefaultRequestCulture = new RequestCulture(new CultureInfo("en-US"),
new CultureInfo("en-US"))
};
app.UseRequestLocalization(requestLocalizationOptions);
}
这就是我在 ActionFilter 中改变 OnActionExecuting 内部文化的方式
actionContext.HttpContext.Response.Cookies.Append(
CookieRequestCultureProvider.DefaultCookieName,
CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) });
CultureInfo.CurrentCulture = culture;
CultureInfo.CurrentUICulture = culture;
我也试过在我的控制器上这样做,但没有运气。
然后在我看来,我用.@inject IViewLocalizer Localizer
来显示本地化字符串@Localizer["Name"]
。
我的资源位于Resources/Views/ControllerName文件夹中,如下所示:
- 资源/视图/ControllerName/ViewName.en.resx
- 资源/视图/ControllerName/ViewName.sl.resx
- ...
无论我如何尝试改变文化,显示的字符串始终来自.en资源文件。有什么我想念的吗?还有什么我应该做的吗?看来我遇到的问题是设置语言。根据文档,您应该将cookie设置为Response.Cookies.Append
,但我也尝试过CultureInfo.CurrentCulture
as Thread.CurrentThread.CurentCulture
is not awailable 。
我真的不知道我错过了什么。有什么想法吗?