MVC验证:在哪里验证? [英] MVC validation: where to validate?

查看:105
本文介绍了MVC验证:在哪里验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们说在控制器层进行模型验证是验证我们将要使用的所有数据的正确位置.在这种情况下,如果我们将UI更改为另一个(记住我们的层必须完全分离),则将执行新的数据验证原理-在这种情况下,我们所有的内部规则都将受到违反. 您可能会说数据模型是单独的层,并且该层(而不是UI)是唯一的验证位置.但是在这种情况下,我发现在服务或业务对象层中验证数据更有效,不是吗? 实际上,我们有许多与域对象相对应的对象:db表记录,linq2sql类,域对象类,viewmodel类.应该只是一个验证数据模型的地方吗?为什么要在(或接近)UI中而不是在另一层中?我认为,验证必须与其他所有业务逻辑一起在服务层中进行.如果我需要尽快通知用户有关错误的信息,除了主要验证之外,我还将使用客户端验证.有什么想法吗?谢谢.

We say that model validation at controllers layer is the correct place to validate all data we gonna operate with. In this case, if we change UI to another (remembering that our layers must be pretty decoupled) the new data validation principles are going to execute - in this case all our inner rules can be violated. You may say that data models is the separate layer and that layer, but not UI, is the only place for validation. But in this case i found it more effective to validate data in the service or business objects layer, don't i? In fact we have a number of objects corresponding to our domain object: db table record, linq2sql class, domain object class, viewmodel class. Should it be only one place to validate data model? Why should it be in (or close to) UI but not in the other layer? In my opinion, the validation must occur in the service layer - with all other busness logic. If i need to inform user about error as fast as possible, i'll use client validation in addition to main one. Thoughts? Thank you.

推荐答案

数据验证是模型的责任.我认为验证规则的最佳位置是数据库中的约束.具有约束条件可确保无论如何访问,都不会在数据库中存储任何不正确的数据.不幸的是,只有基本约束适合在数据库中表达.

Data validation is the responsibility of the model. The best place to put validation rules in my opinion is as constraints in the database. Having constraints ensures that no incorrect data will ever be stored in the database, no matter how it is access. Unfortunately only basic constraints are suitable to express in the database.

下一个放置验证的地方,当使用linq-to-sql进行数据访问时,我是实体类上的扩展方法.然后所有代码都必须通过验证.

The next place to put validation, when using linq-to-sql for data access, I is the extension methods on the entity classes. Then all code will have to pass through the validation.

为了改善用户体验,可以在UI中重复进行基本验证,但这仅是为了用户体验并尽早发现最常见的错误.在网络上,最好使用JavaScript验证.在富客户端上,有时可以重用与扩展方法调用的代码相同的代码.

To improve user experience, basic validation can be repeated in the UI, but that is just for user experience and to catch the most common mistakes early. On the web, using JavaScript validation is preferable. On rich clients the same code as the one called by the extension methods can sometimes be reused.

始终记住,暴露给客户端的任何服务都可能被缺乏真实客户端验证功能的恶意客户端调用.永远不要信任客户端正确地进行任何形式的验证或安全检查.

Always remember that any service exposed to a client, could be called by a malicious client that lacks the validation that the real client does. Never trust the client to do any kind of validation or security checks correctly.

这篇关于MVC验证:在哪里验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆