c# - 流利验证 : set custom message on custom validation

标签 c# fluentvalidation custom-errors

场景

我有一个自定义规则来验证订单的运费:

public class OrderValidator : BaseValidator<Order>
{

    private string CustomInfo { get; set; }

    public OrderValidator()
    {
        //here I call the custom validation method and I try to add the CustomInfo string in the message
        RuleFor(order => order.ShippingCost).Cascade(CascadeMode.StopOnFirstFailure).NotNull().Must(
            (order, shippingCost) => CheckOrderShippingCost(order, shippingCost)
        ).WithMessage("{PropertyName} not set or not correct: {PropertyValue}." + (String.IsNullOrEmpty(CustomInfo) ? "" : " " + CustomInfo));
    }

    //this is the custom validation method
    private bool CheckOrderShippingCost(Order o, decimal shippingCost)
    {
        bool res = false;

        try
        {
            /*
             * check the actual shippingCost and set the res value
             */
        }
        catch (Exception ex)
        {
            CustomInfo = ex.ToString();
            res = false;
        }

        return res;
    }
}

如果出现异常,我将异常信息存储到 CustomInfo 私有(private)成员中,并将其添加到验证消息中。

然后我运行验证器:

OrderValidator oVal = new OrderValidator();
oVal.Results = oVal.Validate(order);
if (!oVal.Results.IsValid)
    oVal.Results.Errors.ForEach(delegate(ValidationFailure error) {
        Console.WriteLine(error.ErrorMessage);
    });

问题

一切正常,在异常情况下 CustomInfo 被正确设置为 ex.ToString() 值。但最终显示在控制台中的错误消息并没有显示 CustomInfo,而是只显示了消息的第一部分:

      "Shipping Cost not set or not correct: 5.9"

问题

为什么自定义消息不包含CustomInfo字符串? 是否可以通过其他方式将异常信息添加到自定义消息中?

最佳答案

根据这个https://fluentvalidation.codeplex.com/wikipage?title=Customising&referringTitle=Documentation&ANCHOR#CustomError

你应该使用

.WithMessage("{PropertyName} not set or not correct: {PropertyValue}. {0}", order => order.CustomInfo);

这将要求您的 CustomInfo 在 Order 类级别,而不是您的验证器类

编辑

你可以使用:

public static class OrderExtensions
{
    private static IDictionary<Order,string> customErrorMessages;

    public static void SetError(this Order order, string message) {
        if (customErrorMessages == null) {
            customErrorMessages = new Dictionary<Order,string>();
        }
        if (customErrorMessages.ContainsKey(order)) {
            customErrorMessages[order] = message;
            return;
        }
        customErrorMessages.Add(order, message);
    }

    public static string GetError(this Order order) {
        if (customErrorMessages == null || !customErrorMessages.ContainsKey(order)) {
            return string.Empty;
        }
        return customErrorMessages[order];
    }
}

对您的验证器进行一些小改动

public class OrderValidator : BaseValidator<Order>
{
    public OrderValidator()
    {
        //here I call the custom validation method and I try to add the CustomInfo string in the message
        RuleFor(order =>     order.ShippingCost).Cascade(CascadeMode.StopOnFirstFailure).NotNull().Must(
            (order, shippingCost) => CheckOrderShippingCost(order, shippingCost)
        ).WithMessage("{PropertyName} not set or not correct: {PropertyValue}. {0}", order => order.GetError()));
    }

    //this is the custom validation method
    private bool CheckOrderShippingCost(Order o, decimal shippingCost)
    {
        bool res = false;

        try
        {
            /*
             * check the actual shippingCost and set the res value
             */
        }
        catch (Exception ex)
        {
            order.SetError(ex.ToString());
            res = false;
        }
        return res;
    }
}

关于c# - 流利验证 : set custom message on custom validation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25135658/

相关文章:

c# - 具有 LDAP 身份验证的 Asp.Net Core 2.1 身份

asp.net-mvc - 在 FluentValidation 中覆盖默认的 ASP.NET MVC 消息

c# - UnityContainer 解决新实例问题

c# - 模拟子验证器时 FluentValidation 抛出 NullReference 异常

c# - 使用 FluentValidation.NET 进行条件规则评估

C# Remoting - 如何关闭 CustomErrors

asp.net - 有没有办法在 IIS 中仅显示网站的某些部分的自定义错误页面?

ASP.NET customErrors with mode=remoteOnly 和 global.asax 处理异常

c# - KnockoutJS 的购物车逻辑(?)问题

c# - ActiveX 控件名称不可用