Public classMyAuthorizeAttribute:System.Web.Mvc.AuthorizeAttribute { Public New string[] Roles {Get;Set; } protected Override BOOLAuthorizecore (HttpContextBase HttpContext) {BOOLresult =false; if(HttpContext = =NULL) { Throw NewArgumentNullException ("HttpContext"); } if(!httpContext.User.Identity.IsAuthenticated) {}if(Roles! =NULL&&Roles.any (HttpContext.User.IsInRole)) {Result=true; } if(!result) {HttpContext.Response.StatusCode=403; } returnresult; } Public Override voidonauthorization (System.Web.Mvc.AuthorizationContext filtercontext) {stringControllername =FilterContext.ActionDescriptor.ControllerDescriptor.ControllerName; stringActionName =FilterContext.ActionDescriptor.ActionName; stringroles =getactionroles (ActionName, controllername); if(!string. Isnullorwhitespace (roles)) { This. Roles = Roles. Split (New string[] {","}, Stringsplitoptions.removeemptyentries); } Base. Onauthorization (Filtercontext); if(FilterContext.HttpContext.Response.StatusCode = =403) {Filtercontext.result=NewRedirectresult ("http://www.baidu.com/"); } } Private stringGetactionroles (stringActionstringController) {XElement rootelement= Xelement.load (HttpContext.Current.Server.MapPath ("/") +"Actionroles.xml"); XElement controllerelement= Findelementbyattribute (RootElement,"Controller", Controller); if(Controllerelement! =NULL) {XElement actionelement= Findelementbyattribute (Controllerelement,"Action", action); if(Actionelement! =NULL) { returnActionelement.value; } } return ""; } PrivateXElement Findelementbyattribute (XElement XElement,stringTagName,stringattribute) { returnXelement.elements (TagName). FirstOrDefault (x = X.attribute ("name"). Value.equals (attribute, stringcomparison.ordinalignorecase)); } }
<?XML version= "1.0" encoding= "Utf-8"?><Roles> <Controllername= "Home"> <Actionname= "Index"></Action> <Actionname= "about">User</Action> <Actionname= "Contact">Admin</Action> <Actionname= "Tips">Admin</Action> </Controller></Roles>
Using Websecurity authentication method, equivalent to the normal way to save the login information in the session.
Websecurity Role Authentication