【问题标题】:Use my custom FluentValidation error message instead of the default one使用我的自定义 FluentValidation 错误消息而不是默认错误消息
【发布时间】:2022-01-11 16:38:17
【问题描述】:

我有以下枚举:

public enum Category
{
Fruits = 0,
Vegetables = 1,
Others = 2
}

领域层中的属性:

public List<Category> Category { get; set; }

当我使用 POST 创建资源时,如果在 Category 中输入的值不存在于枚举中,我会收到以下错误:

“错误”:{“$.category[0]”:[ "无法将 JSON 值转换为 Domain.Category。路径:$.category[0] | LineNumber:6 | BytePositionInLine: 23。"]}

我想使用 FluentValidation 来代替这个错误。

我尝试了RuleFor(x =&gt; x.Category.ToString()).IsEnumName(typeof(Category));,但没有成功。

您知道如何使用我的消息错误吗?例如:.WithMessage("The category {x} doesn't exist")

【问题讨论】:

  • 请发布您的验证规则。但听起来 JSON 解析失败了。
  • 尝试添加到构造函数 Category = new List();

标签: c# json validation fluentvalidation


【解决方案1】:

看例子:

void Main()
{
    
    var t = new Customer();
    t.Category.Add(Category.Fruits);
    t.Dump();
    
    var x = new CustomerValidator();
    x.Validate(t).Dump();
    
}

public class CustomerValidator : AbstractValidator<Customer>
{
    public CustomerValidator()
    {
        RuleFor(x => x.Category).Empty().WithMessage("not empty");
        RuleFor(x => x.Category).IsInEnum().WithMessage("in enum");
    }
}

public class Customer
{
    public List<Category> Category { get; set; }
    public Customer(){
        Category = new List<Category>();
    }
}
public enum Category
{
    Fruits = 0,
    Vegetables = 1,
    Others = 2
}

【讨论】:

  • 你能具体说明修复是什么吗?我所看到的只是一大堆代码和一个屏幕截图。请edit您的回答包含有关如何解决 OP 问题的更明显的摘要。
  • exaple 包含如何“您知道如何使用我的消息错误吗?”。调用如 RuleFor(x => x.Category).Empty().WithMessage("not empty");
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-24
  • 2018-11-17
  • 2011-08-14
相关资源
最近更新 更多