asp.netmvc中基于角色的自定义用户授权我面临的问题是如何让mvc检查我的用户表中的角色是否与我的控制器上的[Authorize(Role)]匹配,以便httpauthorised设置为true。下面是我的自定义类。[AttributeUsage(AttributeTargets.Method|AttributeTargets.Class,Inherited=true,AllowMultiple=true)]publicclassCustomAuthorizeAttribute:AuthorizeAttribute{公共覆盖无效OnAuthorization(AuthorizationContextfilterContext){base.OnAuthorization(filterContext);if(!filterContext.HttpContext.User.Identity.IsAuthenticated){filterContext.Controller.TempData["ErrorDetails"]="您必须登录才能访问此页面";filterContext.Result=newRedirectResult("~/User/Login");返回;}if(filterContext.HttpContext.Request.IsAuthenticated){using(vardb=newGManagerDBEntities()){varauthorizedRoles=(fromuindb.Userswhereu.Username==filterContext.HttpContext.User.Identity.Nameselectu.Role).FirstOrDefault();角色=String.IsNullOrEmpty(角色)?authorizedRoles.ToString():角色;}}if(filterContext.ResultisHttpUnauthorizedResult){filterContext.Controller.TempData["ErrorDetails"]="Youdonathavenecessary权限访问此页面";filterContext.Result=newRedirectResult("~/User/Login");return;}}publicCustomAuthorizeAttribute(paramsobject[]roles){if(roles.Any(r=>r.GetType().BaseType!=typeof(Enum)))thrownewArgumentException("roles");this.Roles=string.Join(",",roles.Select(r=>Enum.GetName(r.GetType(),r)));}}下面是我的装饰器控制器[CustomAuthorize(Role.Administrator)][HttpGet]publicActionResultCreateEmployees(){returnView();}和我的角色publicenumRole{Administrator=1,UserWithPrivileges=2,User=3,}andmodelpublicclassUserModel{publicintUserID{get;set;}[Required][Display(Name="Username:")]publicstringUsername{get;set;}[Required]publicstringPassword{get;set;}publicintRole{get;set;}}查看意见中的链接clearreverend我正在尝试解决这个问题,但我似乎无法将其拼凑在一起MVC3授权自定义角色http://forums.asp.net/p/1573254/3948388.aspxMVC4中带有角色的自定义授权属性使用@VikasRana共享的链接http://www.codeproject.com/Articles/578374/AplusBeginner-splusTutorialplusonplusCustomplusF我摆脱了我的枚举角色和我的方法onAuthorization方法,我将其更改为:`publicoverridevoidOnAuthorization(AuthorizationContextfilterContext){base.OnAuthorization(filterContext);如果(!filterContext.HttpContext.User.Identity.IsAuthenticated){filterContext.Controller。TempData["ErrorDetails"]="您必须登录才能访问此页面";filterContext.Result=newRedirectResult("~/User/Login");返回;}if(filterContext.ResultisHttpUnauthorizedResult){filterContext.Controller.TempData["ErrorDetails"]="您没有访问该页面的权限";filterContext.Result=newRedirectResult("~/User/Login");返回;}}并添加到我的global.asax中得到了这个。protectedvoidApplication_PostAuthenticateRequest(Objectsender,EventArgse){if(FormsAuthentication.CookiesSupported==true&&Request.IsAuthenticated==true){if(Request.Cookies[FormsAuthentication.FormsCookieName]!=null){try{//让我们采取现在输出用户名stringusername=FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;字符串角色=string.Empty;使用(GManagerDBEntitiesdb=newGManagerDBEntities()){Useruser=db.Users.SingleOrDefault(u=>u.Username==username);角色=用户。角色;}//让我们从我们自己的自定义cookie中提取角色//让我们用我们的用户特定详细信息设置PricipalHttpContext.Current.User=newSystem.Security.Principal.GenericPrincipal(newSystem.Security.Principal.GenericIdentity(username,"表格"),roles.Split(';'));}catch(Exception){//somethingwentwrong}}}}上面的方法并不想。它可以为每个简单的页面请求运行大约3次或更多次。所以这里是解决方案2:更好的解决方案实现自定义角色提供者,因为我们已经在使用自定义角色实现。只需点击此链接http://techbrij.com/custom-roleprovider-authorization-asp-net-mvc感谢Gotalove在Global.asax中使用此方法。对于任何尝试使用实体框架进行自定义表单身份验证(FormsAuthentication、FormsAuthenticationTicket)的人,这里有一些帮助。登录控制器SetAuthTicketprotectedvoidGetRoles(intUserID){vardb=newResearchSurveysEntities();字符串[]getRoles={};尝试{varquery=frompindb.UserProfilesjoiniindb.webpages_UsersInRolesonp.UserIdequalsi.UserIdjoinrindb.webpages_Rolesoni.RoleIdequalsr.RoleIdwherep.UserId==UserIDselectnew{p.UserId,r.RoleName};if(query.Count()>0){列表gRoles=newList();foreach(variteminquery){gRoles.Add(item.RoleName);}getRoles=gRoles.ToArray();}roles=String.Join("|",getRoles);}catch(Exceptionex){WebUtilitieswu=newWebUtilities();wu.NotifyWebmaster(ex.ToString(),"获取AdminUserID的角色:"+UserID.ToString(),string.Empty,"登录错误");}最后{db.Dispose();}}WebConfigGlobal.asax(来自上面的例子)以上是C#学习教程:asp.netmvc中基于角色的自定义用户授权。C#学习教程,希望大家多多关注——protectedvoidApplication_AuthenticateRequest(Objectsender,EventArgse){HttpCookieauthCookie=Context.Request.Cookies[FormsAuthentication.FormsCookieName];如果(authCookie==null||authCookie.Value=="")返回;FormsAuthenticationTicketauthTicket;尝试{authTicket=FormsAuthentication.Decrypt(authCookie.Value);}抓住{回报;}//从UserData中检索角色string[]roles=authTicket.UserData.Split('|');如果(Context.User!=null)Context.User=newGenericPrincipal(Context.User.Identity,roles);}本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如有转载请注明出处:
