The MVC framework is a tool for developing web sites, and the MVC framework is starting to get more and more popular. For. NET, Microsoft has also released the MVC framework, where Web sites typically involve user rights management, and how should the user rights management of the. NET MVC framework be set? The following example explains how to implement. NET MVC user Rights Management.
View Microsoft MSDN Library We know that asp.net MVC permission control is a Onauthorization method that implements the Authorizeattribute class. So we need to inherit a class from the Authorizeattribute class and implement the Onauthorization method. As the following code we build a Customauthorizeattribute class
| The code is as follows |
Copy Code |
| Using System; Using System.Collections.Generic; Using System.Linq; Using System.Web; Using SYSTEM.WEB.MVC; Using System.Web.Routing; /// Summary description for Customauthorizeattribute /// Public class Customauthorizeattribute:authorizeattribute { public override void Onauthorization (AuthorizationContext filtercontext) { bool isauthenticated=httpcontext.current.session["User"]==null?false:true; if (!isauthenticated) { filtercontext.result = new Redirecttorouteresult (New RouteValueDictionary (New {controller = "account", action = "Login", ReturnUrl = Filtercontext. HTTPCONTEXT.REQUEST.URL, ReturnMessage = "You do not have permission to view."}); return; } Base. Onauthorization (Filtercontext); } } |
The above code assumes that the user login ID is stored in session, key is user, so by judging whether there is this identity as a sign of login, of course, the user login ID here is only an example, you can completely according to your own method to achieve isauthenticated login judgment. If you do not log on, the code above is redirected to the login page.
So we now have the customauthorizeattribute tag, just give us the [Customauthorizeattribute] tag on the action method, like the following code:
| The code is as follows |
Copy Code |
Using System; Using System.Collections.Generic; Using System.Linq; Using System.Web; Using SYSTEM.WEB.MVC; Namespace Samplemvcwebsite.controllers { public class Homecontroller:controller { // Get:/home/ [Customauthorize] Public ActionResult Index () { return View (); } } } |
The above code would have the effect that when accessing the HomeController Index method, it first executes the Customauthorizeattribute class
Onauthorization to determine whether to log in, if not to jump to the login page.
The
is a coarser-grained solution like the one above, and it is not possible to implement user-defined permission control because the fixed code with the defined permissions is already on the corresponding action. The next tutorial explains. NET MVC role-based Permission control system