This information is different for each user, but is often applied, so it is stored in the Session.
1/** // <summary>
2 // obtain User Permissions
3 /// </summary>
4 // <param name = "userID"> User ID </param>
5 /// <returns> User permission array </returns>
6 public static Int32 [] GetUserPermission (int userID)
7 {
8 // if the permission list information already exists in the cache, it is read directly from the cache.
9 if (HttpContext. Current. Session ["Permission"] = null)
10 {
11 // obtain the user permission from the database, put the permission ID in the int array, and store it in the Session
12 UrlAuthorizeEntities db = new UrlAuthorizeEntities ();
13 var permissions = db. PermissionList. Where (c => c. UserID = userID). Select (c => c. PermissionID). ToArray ();
14 HttpContext. Current. Session ["Permission"] = permissions;
15}
16 return (Int32 []) HttpContext. Current. Session ["Permission"];
17}
18
Create a new UrlAuthorizeAttribute class that inherits from AuthorizeAttribute, which is a Filter. We rewrite its OnAuthorization method to fulfill it in the ASP. NET page lifecycle authentication phase.
1/** // <summary>
2 // rewrite OnAuthorization
3 /// </summary>
4 /// <param name = "filterContext"> </param>
5 public override void OnAuthorization (AuthorizationContext filterContext)
6 {
7 // obtain the permission item list
8 List <PermissionItem> pItems = AccountHelper. GetPermissionItems ();
9
10 // obtain the permission ID corresponding to the current access page. If item is empty, the current page does not have permission control information and does not need permission control.
11 var item = pItems. FirstOrDefault (c => c. Route = filterContext. HttpContext. Request. Path );
12
13 if (item! = Null)
14 {
15 if (Array. indexOf <Int32> (AccountHelper. getUserPermission (int. parse (filterContext. httpContext. session ["UserID"]. toString (), item. permissionID) =-1)
16 {
17 // prompt that the permission is insufficient. You can also jump to another page
18 filterContext. HttpContext. Response. Write ("You are not authorized to visit this page ");
19 filterContext. HttpContext. Response. End ();
20}
21}
22 else
23 {
24 // if the permission ID corresponding to the current page does not exist in the permission item list, all users are not allowed to access the page, prompting them that they are not authorized to access the page. * ** Note 1 ***
25 filterContext. HttpContext. Response. Write ("You are not authorized to visit this page ");
26 filterContext. HttpContext. Response. End ();
27}
28}
29
So far, the first task has been completed. Next, we only need to add [UrlAuthorize] before the Action or Controller that requires URL-based permission control. These Actions or all Actions in the Controller will be actively processed by the Filter UrlAuthorize.