c# - 如何在 ASP.NET Core 中本地化验证属性的标准错误消息
问题描述
如何本地化 ASP.NET Core (v2.2) 中验证属性的标准错误消息?例如,[Required]属性有这个错误信息“ The xxx field is required. ”;[EmailAddress]有“ xxx 字段不是有效的电子邮件地址。 ”;【比较】有“ ‘xxx’和‘yyy’不匹配。 ”等等。在我们的项目中,我们不使用英语,我想找到一种方法来翻译标准错误消息,而无需将它们直接写入每个数据模型类的每个属性中
解决方案
如果您只想本地化错误消息而不是构建多语言站点,您可以试试这个:(消息字符串可能是您的语言。)
- 添加自定义
IValidationMetadataProvider
:
public class MyModelMetadataProvider : IValidationMetadataProvider
{
public void CreateValidationMetadata(ValidationMetadataProviderContext context)
{
if (context == null)
{
throw new ArgumentNullException();
}
var validators = context.ValidationMetadata.ValidatorMetadata;
// add [Required] for value-types (int/DateTime etc)
// to set ErrorMessage before asp.net does it
var theType = context.Key.ModelType;
var underlyingType = Nullable.GetUnderlyingType(theType);
if (theType.IsValueType &&
underlyingType == null && // not nullable type
validators.Where(m => m.GetType() == typeof(RequiredAttribute)).Count() == 0)
{
validators.Add(new RequiredAttribute());
}
foreach (var obj in validators)
{
if (!(obj is ValidationAttribute attribute))
{
continue;
}
fillErrorMessage<RequiredAttribute>(attribute,
"You must fill in '{0}'.");
fillErrorMessage<MinLengthAttribute>(attribute,
"Min length of '{0}' is {1}.");
fillErrorMessage<MaxLengthAttribute>(attribute,
"Max length of '{0}' is {1}.");
fillErrorMessage<EmailAddressAttribute>(attribute,
"Invalid email address.", true);
// other attributes like RangeAttribute, CompareAttribute, etc
}
}
private void fillErrorMessage<T>(object attribute, string errorMessage,
bool forceOverriding = false)
where T : ValidationAttribute
{
if (attribute is T validationAttribute)
{
if (forceOverriding ||
(validationAttribute.ErrorMessage == null
&& validationAttribute.ErrorMessageResourceName == null))
{
validationAttribute.ErrorMessage = errorMessage;
}
}
}
}
- 在中添加一些行
Startup.cs
:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews()
.AddMvcOptions(m => {
m.ModelMetadataDetailsProviders.Add(new MyModelMetadataProvider());
m.ModelBindingMessageProvider.SetValueMustBeANumberAccessor(
fieldName => string.Format("'{0}' must be a valid number.", fieldName));
// you may check the document of `DefaultModelBindingMessageProvider`
// and add more if needed
})
;
}
查看DefaultModelBindingMessageProvider 的文档
如果您可以用日语阅读,请参阅本文了解更多详细信息。
推荐阅读
- ios - iOS弹出框如何去除阴影
- c++ - 在项目中仅使用 CGAL 4.12 标头
- java - 带有 Java 10 模块的 Spring Boot
- c# - Lidgren 框架中的 NetException
- python - Python:如何加速这种耗尽方法?特里?
- raspberry-pi - Raspberry Pi 上的 Watson IOT Out 节点反复断开连接
- android - 了解适用于 Android 的 Apache Cordova 文件系统
- c++ - 在屏幕上打印整个二叉树
- c# - Xamarin.Forms - 触发 IsBusy 绑定
- c# - 仅允许 TextBox 上的特定键