ASP. net mvc uses code annotations for permission control and background navigation

Source: Internet
Author: User

First look: http://www.cnblogs.com/xiaoqi/archive/2011/01/24/1942880.html

 

Permission control needs to write the controller and Action information to the database. Manual addition is troublesome. Is there a simpler way?

Let's use reflection. We can use code annotation (write the details of permission control in the code using xml annotation) + reflection technology to implement it skillfully.

It can also be used for background navigation.

Effect

/// <IsShow> True </IsShow>
/// <IsHeader> True </IsHeader>
/// <Title> Personal Information </Title>
/// <IsAllowedNoneRoles> False </IsAllowedNoneRoles>
/// <IsAllowedAllRoles> False </IsAllowedAllRoles>

Class UserInfoController {}

 

Background Effect

 

 

XML annotations

/// <IsShow> True </IsShow> indicates whether to display data in the navigation menu.
/// <IsHeader> False </IsHeader> indicates whether the navigation title is usually used for the Controler class.
/// <Title> Select User </Title> Title
/// <IsAllowedNoneRoles> False </IsAllowedNoneRoles> whether anonymous access is allowed
/// <IsAllowedAllRoles> False </IsAllowedAllRoles> whether to allow access by all login users

 

Read XML comments

First configure the MVC project to generate an XML file

Property -- generate -- output

 

Execute the initialization task when the website is started.

// Execute the startup task IoC. ResolveAll (). ForEach (t => t. Execute ());

 

Related code:

///// Start the task // public interface IBootstrapperTask {void Execute ();}

 

Specific implementation code:

Public class InitSystemConfig: Detail {private readonly IDomainObjectFactory _ factory; private readonly metadata _ userRepository; private readonly metadata _ roleRepository; private readonly metadata _ resourceRepository; private readonly DefaultRole [] _ defaultRoles; private readonly DefaultUser [] _ defaultUsers; private readonly DefaultResource [] _ defaultResource S; public InitSystemConfig (IDomainObjectFactory factory, Zookeeper, role roleRepository, role resourceRepository, DefaultRole [] defaultRoles, DefaultUser [] defaultUsers, DefaultResource [] defaultResources) {Check. argument. isNotNull (factory, "factory"); Check. argument. isNotNull (userRepository, "userRepository"); Check. argument. isNotNull (roleRepository, "RoleRepository"); Check. argument. isNotNull (defaultRoles, "defaultRoles"); Check. argument. isNotNull (defaultUsers, "defaultUsers"); _ factory = factory; _ region = region; _ resourceRepository = resourceRepository; _ defaultRoles = defaultRoles; _ defaultUsers = defaultUsers; _ defaultResources = defaultResources;} public void Execute () {CreateResourc EIfNotrExist (); createdefacontroller controller (); CreateRoleIfNotExist (); CreateUserIfNotrExist ();} // creates records for controllers and actions without configuration information, by default, it is accessible to all users. // void createdefacontroller controller () {using (IUnitOfWork unitOfWork = UnitOfWork. begin () {IConfigurationManager configurationManager = IoC. resolve (); var assemblyName = configurationManager. appSettings ["WebAssemblyName"]; if (string. isNullOrEmpty (assemblyName )) {AssemblyName = "MarkerPlatform. web ";} Assembly assembly = Assembly. load (assemblyName); Type [] types = assembly. getTypes (); var assemblyXml = HttpContext. current. server. mapPath ("~ /Bin/"+ assemblyName + ". xml "); XmlDocument assembleDoc = new XmlDocument (); if (File. exists (assemblyXml) assembleDoc. load (assemblyXml); foreach (Type type in types) {if (type. baseType! = Null) {if (type. name. contains ("Controller") & type. baseType. name = "BaseController") {// query whether the database has the controler information var controllerName = type. name. replace ("Controller", ""); var dbController = _ resourceRepository. findController (controllerName); // The controller is empty or everyone is allowed to access and anonymous users are not allowed to access // If anonymous users are allowed to access, by default, all actions of this controller can access if (dbController = null | dbController. isAllowedAllRoles &&! DbController. IsAllowedNoneRoles) {if (dbController = null) {// get controller dbController = GetController (assembleDoc, type, controllerName); if (dbController! = Null) _ resourceRepository. add (dbController);} // obtain method information MethodInfo [] myMethodInfo = type. getMethods (); try {foreach (var methodInfo in myMethodInfo) {if (methodInfo. returnType. name = "ActionResult") {var actionName = methodInfo. name; var dbresource = _ resourceRepository. findAction (controllerName, actionName); if (dbresource = null) {// It is set to allow all users to access dbresource = GetDbresource (assembleDoc, con TrollerName, methodInfo, actionName); if (dbresource! = Null) _ resourceRepository. add (dbresource) ;}}} catch (Exception ex) {Console. write (ex) ;}}}} unitOfWork. commit ();}} ////// create an object for the method //////// // private IResource GetDbresource (XmlDocument assembleDoc, string controllerName, methodInfo methodInfo, string actionName) {IResource dbresource; dbresource = _ factory. createResource (actionName, controllerName, false, false, true ); Var path = "M:" + methodInfo. declaringType. fullName + ". "+ methodInfo. name; XmlNode node = GetNode (assembleDoc, path); if (node = null) {dbresource. isHeader = false; dbresource. isShow = false; dbresource. title = controllerName + "/" + actionName;} else {var child = node. selectSingleNode ("IsShow"); dbresource. isShow = child! = Null & bool. Parse (child. InnerText); child = node. SelectSingleNode ("IsHeader"); dbresource. IsHeader = child! = Null & bool. parse (child. innerText); child = node. selectSingleNode ("Title"); if (child = null) child = node. selectSingleNode ("summary"); dbresource. title = child! = Null? Child. innerText. trim (): ""; if (string. isNullOrEmpty (dbresource. title) {dbresource. title = controllerName + "/" + actionName;} child = node. selectSingleNode ("IsAllowedAllRoles"); dbresource. isAllowedAllRoles = child! = Null & bool. Parse (child. InnerText); child = node. SelectSingleNode ("IsAllowedNoneRoles"); dbresource. IsAllowedNoneRoles = child! = Null & bool. parse (child. innerText);} return dbresource;} // create an object for the Controller // private IResource GetController (XmlDocument assembleDoc, type type, string controllerName) {IResource dbController; XmlNode controllerNode = GetNode (assembleDoc, "T:" + type. fullName); // by default, anonymous users are not allowed to access dbController = _ factory. createResource (controllerName, controllerName, true, false, true); if (ControllerNode! = Null) {var child = controllerNode. SelectSingleNode ("IsShow"); dbController. IsShow = child! = Null & bool. Parse (child. InnerText); child = controllerNode. SelectSingleNode ("IsShow"); dbController. IsHeader = child! = Null & bool. parse (child. innerText); child = controllerNode. selectSingleNode ("Title"); if (child = null) child = controllerNode. selectSingleNode ("summary"); dbController. title = child! = Null? Child. innerText. trim (): ""; if (string. isNullOrEmpty (dbController. title. trim () {dbController. title = controllerName;} child = controllerNode. selectSingleNode ("IsAllowedAllRoles"); dbController. isAllowedAllRoles = child! = Null & bool. Parse (child. InnerText); child = controllerNode. SelectSingleNode ("IsAllowedAllRoles"); dbController. IsAllowedAllRoles = child! = Null & bool. parse (child. innerText);} else {dbController. isHeader = false; dbController. isShow = false; dbController. title = controllerName;} return dbController;} private XmlNode GetNode (XmlDocument assembleDoc, string name) {var nodes = assembleDoc. selectNodes ("/doc/members/member"); XmlNode node = null; if (nodes! = Null) foreach (XmlNode xmlNode in nodes) {if (xmlNode. Attributes! = Null) if (xmlNode. attributes ["name"]. value. contains (name) {node = xmlNode; break;} return node;} void CreateRoleIfNotExist () {using (IUnitOfWork unitOfWork = UnitOfWork. begin () {foreach (var role in _ defaultRoles) {var dbRole = _ roleRepository. getByName (role. name); if (dbRole = null) {dbRole = _ factory. createRole (role. name, role. description); // Add Resource var resources = role. resources. S Plit (','); foreach (var resourceName in resources) {var defaultResource = IoC. Resolve (resourceName); if (defaultResource! = Null) {if (String. IsNullOrEmpty (defaultResource. Name) {continue;} var resource = defaultResource. IsController? _ ResourceRepository. FindController (defaultResource. Name): _ resourceRepository. FindAction (defaultResource. ControllName, defaultResource. Name); if (resource! = Null) {dbRole. addResouce (resource) ;}}_ roleRepository. add (dbRole) ;}} unitOfWork. commit () ;}} void CreateUserIfNotrExist () {using (IUnitOfWork unitOfWork = UnitOfWork. begin () {foreach (var user in _ defaultUsers) {// account is email var dbUser = _ userRepository. findByAccountName (user. email); if (dbUser = null) {dbUser = _ factory. createUser (user. email, user. name, user. password ,"","" ); DbUser. Gender = user. Gender; var role = _ roleRepository. GetByName (user. Role. Name); if (role! = Null) {dbUser. addToRole (role);} _ userRepository. add (dbUser) ;}} unitOfWork. commit () ;}} void CreateResourceIfNotrExist () {using (IUnitOfWork unitOfWork = UnitOfWork. begin () {foreach (var resource in _ defaultResources) {var dbresource = resource. isController? _ ResourceRepository. findController (resource. name): _ resourceRepository. findAction (resource. controllName, resource. name); if (dbresource = null) {dbresource = _ factory. createResource (resource. name, resource. controllName, resource. isController, resource. isAllowedNoneRoles, resource. isAllowedAllRoles); dbresource. isHeader = resource. isHeader; dbresource. isShow = resource. isShow; dbresource. title = resource. title; _ resourceRepository. add (dbresource) ;}} unitOfWork. commit ();}}}

 

Code Description

 

1. Run the command at system startup and put it in Global. asax.

2. Only CreateResourceIfNotrExist records that do not exist are created during each load)

3. Reflection is used for reading the controller and method, and the return value and type are used as the filter conditions.

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.