在ConfigureServices
我做了:
services.AddLocalization(opts => opts.ResourcesPath = "Resources");
services.AddMvc(options => { options.MaxModelValidationErrors = 10; })
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix,
opts => opts.ResourcesPath = "Resources")
.AddDataAnnotationsLocalization(options =>
{
options.DataAnnotationLocalizerProvider = (type, factory) =>
{
var assemblyName = new AssemblyName(typeof(SharedResource).GetTypeInfo().Assembly.FullName);
return factory.Create("SharedResource", assemblyName.Name);
};
});
services.Configure<RequestLocalizationOptions>(options =>
{
var supportedCultures = new[]
{
new CultureInfo("en-US"),
new CultureInfo("en"),
new CultureInfo("it-IT"),
new CultureInfo("it")
};
options.DefaultRequestCulture = new RequestCulture(culture: "en", uiCulture: "en");
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
options.RequestCultureProviders.Insert(0, new AcceptLanguageHeaderRequestCultureProvider());
});
//This is the custom service for localization
services.AddSingleton<LocService>();
在LocService
中创建本地化服务,如:
public class LocService : StringLocalizer<string>
{
private readonly IStringLocalizer _localizer;
public LocService(IStringLocalizerFactory factory) : base(factory)
{
var type = typeof(SharedResource);
var assemblyName = new AssemblyName(type.GetTypeInfo().Assembly.FullName);
_localizer = factory.Create("SharedResource", assemblyName.Name);
}
public override LocalizedString this[string name]
{
get => _localizer[name];
}
}
并在Configure()
中配置了所有内容:
var locOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
app.UseRequestLocalization(locOptions.Value);
在视图中我将其注入:
@inject LocService Loc
@Loc["wordToTranslate"]
我的问题是,当缺少相关资源文件时,这种方法不起作用,例如,
如果我没有Resources / SharedResource.it.resx并且该调用(@Loc["wordToTranslate"]
)只返回"wordToTranslate"
,即使在默认的Resources / SharedResource.en.resx对应另一个字符串({{ 1}})。我做错了什么?
答案 0 :(得分:1)
在ASP.NET Core本地化中,默认语言是放在括号内的语言,因此:
@Localizer["some text"]
将呈现:
或者,如果您想使用资源文件,只需从中移除文化,即someresource.resx