无法将类型“CustomPrincipal”转换为“System.Security.Principal.IPrincip
本文关键字:System Security IPrincip Principal 转换 类型 CustomPrincipal | 更新日期: 2023-09-27 18:35:38
我按照本指南将自定义属性添加到IPrincipal。
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
JavaScriptSerializer serializer = new JavaScriptSerializer();
CustomPrincipalSerializeModel serializeModel = serializer.Deserialize<CustomPrincipalSerializeModel>(authTicket.UserData);
CustomPrincipal newUser = new CustomPrincipal(authTicket.Name);
newUser.UserId = serializeModel.UserId;
newUser.FirstName = serializeModel.FirstName;
newUser.LastName = serializeModel.LastName;
HttpContext.Current.User = newUser; /This line makes an error.
}
}
这是出错的最后一行。
无法将类型"SocialMedia.Models.CustomPrincipal"隐式转换为"System.Security.Principal.IPrincipal"。存在显式转换(您是否缺少强制转换?
为什么它不起作用可能有什么问题。?
错误很明显,您分配给User
属性的实例需要类型 IPrincipal
的实例,我怀疑您的CustomPrincipal
类不是从接口继承IPrinicipal
那是因为您看到了错误。
HttpContext.Current.User = (IPrincipal)newUser;
编辑
确保ICustomPrincipal
扩展了IPrincipal
接口。