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

Cannot convert type 'CustomPrincipal' to 'System.Security.Principal.IPrincipal'

我已按照此 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.
        }
    }

最后一行出错了。

Cannot implicitly convert type 'SocialMedia.Models.CustomPrincipal' to 'System.Security.Principal.IPrincipal'. An explicit conversion exists (are you missing a cast?)

为什么它不工作可能是什么问题?

将最后一行改为:

HttpContext.Current.User = (IPrincipal)newUser;

编辑

确保 ICustomPrincipal 扩展了 IPrincipal 接口。

错误很明显,您分配给 User 属性 的实例需要 IPrincipal 类型的实例,我怀疑您的 CustomPrincipal class 没有继承自 IPrinicipal 接口,那是因为您看到了错误。