我正在使用ASP.NET Core,并尝试本地化应用程序.我设法使用新的 asp .net核心资源来本地化控制器和视图,并使用旧资源来本地化错误消息以进行模型验证.但是,当错误消息未链接到模型字段注释(如"必需")并且模型绑定的数据不正确时(如预期数字的文本),我收到如下错误,我是无法本地化:
"值'abc'对ID无效."
当我进入abc了ID房地产View,因为模型绑定无法做到的领域,它显示为近场验证消息,称"值'ABC’是无效的ID." .这是我正在使用的课程:
public class Country : IHasID
{
public int ID { get; set; }
[Required(ErrorMessageResourceType = typeof(L.Val),
ErrorMessageResourceName = "NameR")]
[MaxLength(100, ErrorMessageResourceType = typeof(L.Val),
ErrorMessageResourceName = "Max")]
public string Name { get; set; }
/*Some other properties*/
}
Run Code Online (Sandbox Code Playgroud)
我在互联网上发现的类似问题要么针对较旧的asp .net版本,否则无法解决问题.
我在新的.NET Core项目中苦苦挣扎.我有2个项目:
我希望在一个地方全局本地化所有验证属性,以获得类似MVC 5的行为.这可能吗?
我不想为模型/视图等提供单独的语言文件.
使用SharedResources.resx文件和本地化的DataAnnotation消息时,Microsofts文档不是很清楚.
在MVC 5中我没有处理它.我只需要将语言环境设置为我的语言,一切都很好.
我尝试将ErrorMessageResourceName和ErrorMessageResourceType设置为DataAccess项目中的共享资源文件名"Strings.resx"和"Strings.de.resx":
[Required(ErrorMessageResourceName = "RequiredAttribute_ValidationError", ErrorMessageResourceType = typeof(Strings))]
Run Code Online (Sandbox Code Playgroud)
我还尝试将设置名称设为RequiredAttribute_ValidationError - 但它不起作用.
我已经.AddDataAnnotationsLocalization()在Startup.cs中添加了 - 但似乎什么也没做.
我读过几篇文章,但我找不到它为什么不起作用的原因.
编辑:我到目前为止:
1.)LocService类
public class LocService
{
private readonly IStringLocalizer _localizer;
public LocService(IStringLocalizerFactory factory)
{
_localizer = factory.Create(typeof(Strings));
}
public LocalizedString GetLocalizedHtmlString(string key)
{
return _localizer[key];
}
}
Run Code Online (Sandbox Code Playgroud)
2.)使用Strings.cs添加了文件夹"Resources"(带有虚拟构造函数的空类)
3.)添加了一个带有"RequiredAttribute_ValidationError"项的Strings.de-DE.resx文件
4.)修改了我的Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<MessageService>();
services.AddDbContext<DataContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddSingleton<LocService>();
services.AddLocalization(options => options.ResourcesPath = "Resources");
services.AddMvc()
.AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver())
.AddDataAnnotationsLocalization( …Run Code Online (Sandbox Code Playgroud)