开发者

Handing complex validation scenarios in ASP.NET MVC

开发者 https://www.devze.com 2022-12-17 13:20 出处:网络
I\'m been working on a GetRuleViolations() method for my User class, but I\'m getting a little hung up on on something:

I'm been working on a GetRuleViolations() method for my User class, but I'm getting a little hung up on on something:

What happens when different actions require different business rules?

My User table has the following columns: Id, UserRoleId, Username, and Password. Several actions involving User are possible (create new user, edit user, set/reset password, and log in), and the business rules for each are not always the same.

For example, when users log in, they are required to enter a password, but when admins create a new user, entering a password is not even an option. And in the case of setting/resetting a password, the password needs to be entered twice, and the two values n开发者_StackOverflow中文版eed to be an exact match. What is the best way to handle this complexity? Is there some kind of design pattern to allow the right GetRulesViolations() method to be selected for the right circumstance?


As to #1, the business rules won't exist in your database, they'll exist in the application, whether in a domain layer, separate business layer, etc... or right in your controllers, depending on your approach.

You'll present a different screen, or view, to a logged-in admin who is creating a user than you will present to an unauthenticated user who is creating an account, right? The HTTP-POST from that view is going to correspond to a different action, which will either handle the logic directly, or delegate to the appropriate object(s). One method will check the provided password and either create a record for the user or redirect the user to some sort of failure page ("passwords don't match" or "username already taken", for example). The other method will create a new user in the database, no questions asked.

Different views posting to different actions, corresponding to different methods, each of which handles a single, specific job/scenario.


I'm finding that a "service layer" to handle validation makes a lot of sense.

I found this tutorial very helpful: http://www.asp.net/learn/mvc/tutorial-38-cs.aspx

Also, it looks as though some nice enhancements to validation are in the works for MVC 2.0 (see http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx). Using a UserService or UserValidator should allow the 2.0 features to be folded in without having to change class design too significantly.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号