[英]Fluent validation: set custom message on custom validation
脚本
我有一个自定义规则来验证订单的运费:
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私有成员中,然后将其添加到验证消息中。
然后我运行验证器:
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字符串? 是否可以以另一种方式将自定义消息添加到异常信息中?
你应该宁愿使用
.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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.