Simple implementation of permission control in ASP. NET MVC

Source: Internet
Author: User

1. Rewrite the AuthorizeAttribute class and use its own permission control logic to override the AuthorizeCore method.


 

Public class MyAuthorizeAttribute: AuthorizeAttribute {protected override bool AuthorizeCore (HttpContextBase httpContext) {string currentRole = (Session ["user"] as User ). role; // obtain the User object from the Session and obtain the Role information. If you have rewritten Identity, you can go to httpContext. current. user. if (Roles. contains (currentRole) return true; return base. authorizeCore (httpContext) ;}} public class MyAuthorizeAttribute: AuthorizeAttribute {protected override bool AuthorizeCore (HttpContextBase httpContext) {string currentRole = (Session ["user"] as User ). role; // obtain the User object from the Session and obtain the Role information. If you have rewritten Identity, you can obtain if (Roles. Contains (currentRole) return true; return base. AuthorizeCore (httpContext) in httpContext. Current. User. Identity );}}

2. Add the corresponding Attribute to the Action that requires permission control and set the role group that can be accessed.


 

MyAuthorize(Roles = "Admin, User")]        public ActionResult AuthorizeMethod2()        {            return View();        }  [MyAuthorize(Roles = "Admin, User")]        public ActionResult AuthorizeMethod2()        {            return View();        }

When the user accesses the corresponding Action, the corresponding permission control is implemented.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.