哪种 MVC 验证框架

发布于 2024-08-12 20:52:08 字数 435 浏览 4 评论 0原文

我一直在评估 xVal 作为在 ASP.Net MVC 框架中验证实体的框架。我最近发现,每次验证规则被破坏时,xVal 都会引发异常。对我来说这似乎是不正确的。例如,当用户填写表单时,忘记填写三个必填字段,则会抛出三个异常。这是好的做法吗? (编辑:我也读过这篇文章,所以我想这不是一个好的做法)

什么是您使用 xVal 的经历?是否有好的替代验证框架不会抛出异常?

谢谢

(PS:我注意到很多人都在读这篇文章,只是为了让你知道我正在使用 Fluent Validation 现在)

I have been evaluating xVal as framework for validating Entities in the ASP.Net MVC Framework. I have recently discovered that each time a validation rule is broken, xVal cause an excpetion to be thrown. To me is seems incorrect. For example, when a user fills in a form, and forgets to fill three required fields , three exceptions will be thrown. Is this good practice? ( Edit: I also read this, so I guess its not good practice)

What are your experiences of using xVal? Is there good alternative validation framework that does not throw exceptions?

Thanks

(PS: I notice that lots of people are reading this, just to let you know I am using Fluent Validation now)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

怎会甘心 2024-08-19 20:52:08

不,显示异常而不是一些简单的消息不是一个好习惯,因为没有出现任何严重错误...您应该使用这些错误填充 ModelState 并使用

Html.ValidationMessage("EntityPropertyName");

xVal 支持所有这些 错误将它们显示在表单上。以及在表单回发之前在客户端进行验证。

一些代码

当您为实体类(或其元数据伴随类)设置 DataAnnotations 属性时,您很可能还会实现 Validate() 方法。最好的方法是使用 T4 自动为你生成这些代码,这样你就不必一遍又一遍地重复相同的代码...

public IEnumerable<ErrorInfo> Validate()
{
    IList<ErrorInfo> errors = DataAnnotationsValidationRunner.GetErrors(this).ToList<ErrorInfo>();
    return errors.AsEnumerable();
}

然后你所要做的就是调用这个:

IEnumerable<ErrorInfo> errors = entityObjectInstance.Validate();
if (errors.Any())
{
    new RulesException(errors).AddModelStateErrors(filterContext.Controller.ViewData.ModelState, entityPropertyName);
}

并进一步自动化,您可以在操作过滤器中实现此功能,因此对于传递到控制器操作的实体对象将自动进行验证。控制器操作只需要检查是否是 ModelState.IsValid()

这里您还需要一门课程(取自网络某处):

public static class DataAnnotationsValidationRunner
{
    public static IEnumerable<ErrorInfo> GetErrors(object instance)
    {
        var metadataAttribute = instance.GetType().GetCustomAttributes(typeof(MetadataTypeAttribute), true).OfType<MetadataTypeAttribute>().FirstOrDefault();
        var metaClass = metadataAttribute != null ? metadataAttribute.MetadataClassType : instance.GetType();
        var metaClassProperties = TypeDescriptor.GetProperties(metaClass).Cast<PropertyDescriptor>();
        var modelClassProperties = TypeDescriptor.GetProperties(instance.GetType()).Cast<PropertyDescriptor>();

        return from metaProp in metaClassProperties
               join modelProp in modelClassProperties on metaProp.Name equals modelProp.Name
               from attribute in metaProp.Attributes.OfType<ValidationAttribute>()
               where !attribute.IsValid(modelProp.GetValue(instance))
               select new ErrorInfo(metaProp.Name, attribute.FormatErrorMessage(string.Empty), instance);
    }
}

MVC 2

Validation in Asp.net MVC 2 Beta 2 与 xVal 的做法类似。因此,如果您对项目的了解不是太深,并且可以考虑使用开发进度中的代码作为基础,也许这就是适合您的方法。

No it's not a good practice to show exceptions instead of some simple messages because nothing seriously has been going wrong... You should instead populate ModelState with these errors and display them on the form using

Html.ValidationMessage("EntityPropertyName");

xVal supports all these. As well as validating on the client side before the form gets posted back.

Some code

When you set DataAnnotations attributes to your entity classes (or their Metadata companion classes) you will most likely also implement Validate() method. the best way would be to use T4 that will auto generate those for you, so you don't have to repeate the same code over and over...

public IEnumerable<ErrorInfo> Validate()
{
    IList<ErrorInfo> errors = DataAnnotationsValidationRunner.GetErrors(this).ToList<ErrorInfo>();
    return errors.AsEnumerable();
}

All you have to do then is to call this:

IEnumerable<ErrorInfo> errors = entityObjectInstance.Validate();
if (errors.Any())
{
    new RulesException(errors).AddModelStateErrors(filterContext.Controller.ViewData.ModelState, entityPropertyName);
}

And to automate this even further, you can implement this in an action filter, so validation will be automatic for your entity objects that get passed into controller action. Controller actions would only need to check whether ModelState.IsValid() then.

One more class you'll need here is (and is taken from the web somewhere):

public static class DataAnnotationsValidationRunner
{
    public static IEnumerable<ErrorInfo> GetErrors(object instance)
    {
        var metadataAttribute = instance.GetType().GetCustomAttributes(typeof(MetadataTypeAttribute), true).OfType<MetadataTypeAttribute>().FirstOrDefault();
        var metaClass = metadataAttribute != null ? metadataAttribute.MetadataClassType : instance.GetType();
        var metaClassProperties = TypeDescriptor.GetProperties(metaClass).Cast<PropertyDescriptor>();
        var modelClassProperties = TypeDescriptor.GetProperties(instance.GetType()).Cast<PropertyDescriptor>();

        return from metaProp in metaClassProperties
               join modelProp in modelClassProperties on metaProp.Name equals modelProp.Name
               from attribute in metaProp.Attributes.OfType<ValidationAttribute>()
               where !attribute.IsValid(modelProp.GetValue(instance))
               select new ErrorInfo(metaProp.Name, attribute.FormatErrorMessage(string.Empty), instance);
    }
}

MVC 2

Validation in Asp.net MVC 2 Beta 2 is similar to what xVal does. So if you're not too far into the project and you can consider using code in development progress as your foundation, maybe that is the way to go for you.

吻安 2024-08-19 20:52:08

我认为 xVal 很棒,我一直将它与 Castle 验证器< /a> 并且它工作得很好。只要在运行验证时捕获 RulesException 并将错误添加到 ModelState 中,例如

try
{
  // execute validation runner
}
catch (RulesException ex)
{
   ex.AddModelStateErrors(ModelState, "prefix");
}

ASP.NET MVC v2 将引入自己的 验证框架

I think xVal is great, I've been using it with Castle Validators and it works perfectly. Just catch the RulesException whenever you're running validation and add the errors to your ModelState, e.g.

try
{
  // execute validation runner
}
catch (RulesException ex)
{
   ex.AddModelStateErrors(ModelState, "prefix");
}

ASP.NET MVC v2 will introduce its own validation framework.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文