如何更改System.ComponentModel.DataAnnotations.ValidationAttribute的默认验证错误

时间:2020-04-14 12:21:17

标签: c# asp.net-core

我有一个如下所示的类(简化),我想用自己的消息替换默认的验证错误。我知道添加属性时可以直接设置消息,但这太麻烦了,在同一代码中添加10,000次相同消息是错误的剪裁。

Public class CreateUser
{
    [Required(ErrorMessage = "A specific message")]//Don't like to do this
    [MinLength(10)]// Like to write specific text 
    public string Name { get; set; }
}

我研究了他们的代码,显然他们正在使用ResourceManager来设置密钥中的实际消息。该文档仅描述了处理Windows应用程序的方法。如何在Asp.net核心应用程序中添加资源并覆盖默认值?

更新

如果您知道如何设置ResourceManager,从代码看来似乎是一个很小的更改,但是从注释来看,这似乎是一项艰巨的工作。我不明白为什么。对于MinLenghtAttribute,我们有

public class MinLengthAttribute : ValidationAttribute
{
public MinLengthAttribute(int length)
        : base(SR.MinLengthAttribute_ValidationError)
    {
        Length = length;
    }
    // The rest of the code
 }

SR如下:

namespace System
{
    internal static partial class SR
    {
   internal static string MinLengthAttribute_ValidationError => 
    GetResourceString("MinLengthAttribute_ValidationError");
    // The rest of the code
    }
 }

一个人应该能够获得GetResourceString中的值并实现我的目标。对?

0 个答案:

没有答案