无法将类型 'CustomPrincipal' 转换为'System.Security.Principal.IPrincipal'



我按照本指南将自定义属性添加到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接口。

相关内容

  • 没有找到相关文章

最新更新