【发布时间】:2015-02-17 17:25:50
【问题描述】:
感谢您的关注,我意识到这个问题有点奇怪。这是我希望实现的目标:
我有什么
我正在使用System.ComponentModel.DataAnnotations 来验证从网页发布的模型。我已经将必要的代码部分抽象成一个共享方法:
public static string Create_Widget(WidgetModel postedWidget)
{
//Validate the model
var errors = HelperMethods.Validate(postedWidget);
if (!string.IsNullOrEmpty(errors))
{
return errors;
}
//Do other stuff
}
还有辅助方法:
public static string Validate<T>(T entity)
{
var context = new ValidationContext(entity, serviceProvider: null, items: null);
var results = new List<ValidationResult>();
Validator.TryValidateObject(entity, context, results);
return string.Join(",", results.Select(s => s.ErrorMessage));
}
我想要什么
我真正想做的只是有一个扩展方法来验证我的模型,而不是在它下面添加一个if statement 来获得条件返回:
public static string Create_Widget(WidgetModel postedWidget)
{
//Validate the model
postedWidget.Validate(); //Automatically returns error string if errors.
//Do other stuff
}
这可能吗?
【问题讨论】:
-
只要抛出验证失败的异常。
-
抛出一个异常并在你想要处理的地方捕获它。
-
感谢@Servy,但最终我需要返回一个以逗号分隔的错误字符串,就像代码当前正在执行的那样。我可以通过简单地抛出异常来做到这一点吗?
-
@MatthewPatrickCashatt 如果异常包含该数据,并且调用者捕获它并提供该数据,当然可以。
-
我认为如果你只返回一个
string,它会更具可读性。
标签: c# validation model data-annotations