FluentValidation:如何将所有验证消息放在一个位置?

Sah*_*rma 6 c# asp.net localization fluentvalidation

这是我的验证类之一:

public class StocksValidator : AbstractValidator<Stocks>
    {
        public StocksValidator()
        {
            RuleFor(x => x.SellerId).GreaterThan(1).WithMessage("SellerId should be greater than 1")
                                    .LessThan(100).WithMessage("SellerId should be less than 100");
            RuleFor(x => x.SellerType).GreaterThan(101).WithMessage("SellerType should be greater than 101")
                                    .LessThan(200).WithMessage("SellerType should be less than 200");
            RuleFor(x => x.SourceId).GreaterThan(201).WithMessage("SourceId should be greater than 201")
                                    .LessThan(300).WithMessage("SourceId should be less than 300");
        }
    }
Run Code Online (Sandbox Code Playgroud)

我知道这些消息,例如{field}应该少于{x}应该位于公共位置,而不是这里。但是我不知道如何集中他们?

  1. 一种方法是使用所有这些常量字符串创建新的c#文件。这很简单。

  2. 在Web API中使用本地化和流畅的验证。这有什么好处。我在哪里可以找到好的教程?

Evg*_*vin 5

如果您需要更改内置规则的默认消息,这将影响包含此规则 \xe2\x80\x94 的所有验证器,请按照以下步骤操作:

\n

1:使用您的自定义资源提供程序类在Startup.cs或处设置流畅的验证global.asax.cs

\n
ValidatorOptions.ResourceProviderType = typeof(MyResourceProvider);\n
Run Code Online (Sandbox Code Playgroud)\n

2:覆盖某些验证规则的默认消息

\n
// create MyResourceProvider.resx to auto-generate this class in MyResourceProvider.Designer.cs file (support multiple cultures out of box),\n// or create class manually and specify messages in code\npublic class MyResourceProvider {\n   public static string greaterthan_error {\n      get { \n          return "{PropertyName} should be greater than {ComparisonValue}, but you entered {PropertyValue}";\n      }\n   }\n   public static string lessthan_error {\n      get { \n          return "{PropertyName} should be less than {ComparisonValue}";\n      }\n   }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

3(可选):使用WithName()方法来替换属性名称的默认输出,使其更加用户友好

\n
RuleFor(x => x.SellerId).GreaterThan(1).WithName("Seller identidier") \n// outputs "Seller identidier should be greater than 1, but you entered 0"\n
Run Code Online (Sandbox Code Playgroud)\n

您可以在FluentValidation github上找到更多信息:

\n

1. 本地化\xe2\x80\x94 在这里您可以找到有关本地化消息(如WithLocalizedMessage方法)的方法的更多信息,以及资源名称,这些名称应在MyResourceProvider.

\n

2. 内置验证器- 在这里您可以找到所有验证规则的替换名称,这些规则应该在错误消息字符串中使用。

\n

3. Messages.resx - 此处放置错误消息的默认资源文件。

\n