[英]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.