我已按照此guide向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.
}
}
这是发生错误的最后一行。
无法隐式转换类型&#39; SocialMedia.Models.CustomPrincipal&#39;到了System.Security.Principal.IPrincipal&#39;。存在显式转换(您是否错过了演员?)
为什么它不起作用可能是什么问题。?
答案 0 :(得分:1)
错误很明显,您分配给User
属性的实例需要IPrincipal
类型的实例,我怀疑您的CustomPrincipal
类不是从IPrinicipal
继承的界面,那是因为你看到了错误。
答案 1 :(得分:0)
将最后一行更改为:
HttpContext.Current.User = (IPrincipal)newUser;
修改强>
确保ICustomPrincipal
扩展了IPrincipal
界面。