【问题标题】:Fluent validation: It is possible to add more error messages?Fluent 验证:是否可以添加更多错误消息?
【发布时间】:2022-06-13 14:06:53
【问题描述】:

我有错误模型,例如

并在我的验证器中进行规则

RuleFor(d => d.Name).NotEmpty().WithMessage("{PropertyName} is required.")

有没有办法添加新的自定义选项,例如

 RuleFor(d => d.Name).NotEmpty().WithMessage("{PropertyName} is required.").**WithCustomErrorMessage("Example message content")**?

编辑: 我想从我的 web api 应用程序返回错误列表。 每个错误看起来都像这样:

public class Error
    {
        public string ErrorName{ get; set; }
        public string ErrorDetails{ get; set; }
        public string ErrorCode{ get; set; }
        public string FieldPath{ get; set; }
    }

我想在验证器中分配这些值,然后使用 ValidationResult 对象在我的处理程序中创建一个错误列表。

感谢您的建议。

【问题讨论】:

标签: c# .net-core fluentvalidation


【解决方案1】:

你为什么不直接编辑'.WithMessage()'里面的属性呢? 编辑:

当您现在编辑问题时,我将在此处添加答案。为了清楚起见,您缺少一些有关如何调用验证器的代码。这是正确回答您的问题所必需的。

假设您想在此处返回所有错误,这实际上是可能的。查看此链接以检索验证中的所有错误https://docs.fluentvalidation.net/en/latest/error-codes.html

【讨论】:

    【解决方案2】:

    我试过了

      public async Task OnActionExecutionAsync(ActionExecutingContext context,
                                           ActionExecutionDelegate next)
            {
                if (!context.ModelState.IsValid)
                {
                    var errors = context.ModelState.Values.Where(v => v.Errors.Count > 0)
                            .SelectMany(v => v.Errors)
                            .Select(v => v.ErrorMessage)
                            .ToList();
    
                    var value = context.ModelState.Keys.ToList();
                    Dictionary<string, string[]> dictionary = new Dictionary<string, string[]>();
                    foreach (var modelStateKey in context.ModelState.Keys.ToList())
                    {   
                       // here you can get your desire data
                        string[] arr = null ;
                        List<string> list = new List<string>();
                        foreach (var error in context.ModelState[modelStateKey].Errors)
                        {
                            // here you can modify as you want 
                            list.Add(error.ErrorMessage);
                        }
                        arr = list.ToArray();
                        dictionary.Add(modelStateKey, arr);
                    }
                    // here you can make your own model and bind data as you want.
                    var responseObj = new 
                    {
                        StatusCode="400",
                        Message = "Bad Request",
                        Errors = dictionary
                    };
     
    
            context.Result = new BadRequestObjectResult(responseObj);
                    return;
                }
                await next(); 
            }
    
    Response Model example:// you can make your own model
    {
        "statusCode": "400",
        "message": "Bad Request",
        "errors": {
            "Channel": [
                "'Channel' must not be empty."
            ],
            "TransactionId": [
                "'TransactionId' must not be empty."
            ],
            "Number": [
                "'Number' must not be empty."
            ]
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-03
      • 2018-11-17
      • 2012-09-11
      • 1970-01-01
      • 2017-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多