在MVC中使用自定义成员资格和角色提供者实现IPrincipal和IIdentity完成。我已经花了一天时间在谷歌上搜索如何实施这些权利并使用更多信息对其进行扩展。我想使用全名或其他自定义变量扩展Information@Context.User.Identity.Name。编辑:现在我得到以下代码,但如果我尝试读取@((CustomPrincipal)Context.User.Identity).Nachname我收到错误消息,System.Web.Security.FormsIdentity无法转换为CustomPrincipal。有什么想法吗?放;}publicStringNachname{get;放;}}AccountModel:publicclassFormsAuthenticationService:IFormsAuthenticationService{publicvoidSignIn(stringuserName,boolcreatePersistentCookie){if(String.IsNullOrEmpty(userName))thrownewArgumentException("DerWertdarfnichtNULLoderleersein.","userName");//抓取用户信息插入KIMembershipUsermembershipUser=(KIMembershipUser)Membership.GetUser(userName);varcustomInfo=String.Format("{0}|{1}",membershipUser.Vorname,membershipUser.Nachname);//创建并加密票证varticket=newFormsAuthenticationTicket(2,//版本号userName,//用户名DateTime.Now,//签发日期DateTime.Now.AddMinutes(30),//到期日期createPersistentCookie,//是它持久吗?//用户数据);varencTicket=FormsAuthentication.Encrypt(ticket);//将票存入cookievarcookie=FormsAuthentication.GetAuthCookie(FormsAuthentication.FormsCookieName,createPersistentCookie);cookie.Value=encTicket;//将cookie附加到响应HttpContext.Current.Response.Cookies.Add(cookie);//FormsAuthentication.SetAuthCookie(用户名,createPersistentCookie);}publicvoidSignOut(){FormsAuthentication.SignOut();}}Global.asax中:protectedvoidApplication_PostAuthenticateRequest(){//收集当前安全信息varprincipal=HttpContext.Current.UserasRolePrincipal;如果(主体==null)返回;varidentity=principal.IdentityasFormsIdentity;如果(身份==null)返回;varroles=principal.GetRoles();//提取身份验证票中的用户数据varcustomInfo=identity.Ticket.UserData;vartokens=customInfo.Split('|');//构建一个更丰富的主体对象varCustomPrincipal=newCustomPrincipal(identity,roles){Vorname=tokens[0],Nachname=tokens[1]};//将新主体存储在HttpContext中HttpContext.Current.User=CustomPrincipal;使用(CustomPrincipal)Context.User)。Nachname代替(CustomPrincipal)Context.User.Identity).Nachname以上是C#学习教程:使用自定义成员资格和角色提供者实现MVC中IPrincipal和IIdentity共享的所有内容,如果对大家有用,需要的话了解更多关于C#学习教程,希望大家多多关注本文——本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
