gpt4 book ai didi

asp.net-mvc - ASP.NET MVC : Is Data Annotation Validation Enough?

转载 作者:行者123 更新时间:2023-12-03 10:15:38 25 4
gpt4 key购买 nike

我在 ASP.NET MVC 2 中广泛使用 Data Annotation 验证。这个新功能节省了大量时间,因为我现在能够在一个地方定义客户端验证和服务器端验证。然而,当我做一些详细的测试时,我意识到如果我只依赖数据注释验证,那么有人很容易绕过服务器端验证。例如,如果我通过使用 [Required] 属性注释属性来定义一个必填字段,并在表单中为该必填字段放置一个文本框,用户可以简单地从 DOM 中删除该文本框(这可以通过 Firebug 轻松完成)现在,在 Controller 内部的 ModelBinding 期间,不会在该属性上触发 Data Annotation 验证。为确保触发“必需”验证,我可以在 ModelBinding 发生后重复验证,但随后我将重复验证逻辑。

大家对验证有什么建议?数据注释验证是否足够?或者是否需要重复验证以确保在所有情况下都会触发验证?

后续评论:
根据下面的答案,我似乎不能单独依赖模型绑定(bind)器和数据注释验证。由于我们得出的结论是需要额外的服务器端验证,我的服务层是否有一种简单的方法可以根据数据注释中定义的内容触发验证?似乎这将使我们两全其美……我们不需要重复验证代码,但即使 Model Binder 没有触发验证,我们仍将确保执行验证。

我将把这个后续评论作为一个单独的问题发布,因为它提出的问题与原来的问题不同。

最佳答案

见代码项目Server-side Input Validation using Data Annotations

Input validation can be done automatically on the client side in ASP.NET MVC or explicitly validating the model against the rules. This tip will describe how it can be done manually on the server-side of an ASP.NET applications or within the repository code of WPF applications.

        // Use the ValidationContext to validate the Product model against the product data annotations
// before saving it to the database
var validationContext = new ValidationContext(productViewModel, serviceProvider: null, items:null);
var validationResults = new List<ValidationResult>();

var isValid = Validator.TryValidateObject(productViewModel, validationContext,validationResults, true);

关于asp.net-mvc - ASP.NET MVC : Is Data Annotation Validation Enough?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1558457/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com