![](/img/trans.png)
[英]Localizing Error Messages In ASP.NET MVC 2 (Default Validation Attributes)
[英]How to localize standard error messages of validation attributes in ASP.NET Core
如何在 ASP.NET Core (v2.2) 中本地化驗證屬性的標准錯誤消息? 例如, [Required]屬性有這個錯誤信息“ The xxx field is required. ”; [EmailAddress]有“ xxx 字段不是有效的電子郵件地址。 ”; 【比較】有“ 'xxx'和'yyy'不匹配。 ”等。 在我們的項目中,我們不使用英語,我想找到一種方法來翻譯標准錯誤消息,而無需將它們直接寫入每個數據模型類的每個屬性中
這在docs 中有詳細說明。 您可以執行以下任一操作:
在屬性上使用ResourcePath
選項。
[Required(ResourcePath = "Resources")]
然后,您將本地化的消息添加到Resources/Namespace.To.MyClass.[lang].resx
。
對所有類使用一個資源文件:
public void ConfigureServices(IServiceCollection services) { services.AddMvc() .AddDataAnnotationsLocalization(options => { options.DataAnnotationLocalizerProvider = (type, factory) => factory.Create(typeof(SharedResource)); }); }
如果您只想本地化錯誤消息而不是構建多語言站點,您可以試試這個:(消息字符串可能是您的語言。)
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 的文檔
如果您能用日語閱讀,請參閱這篇文章了解更多詳情。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.