无法转换类型' CustomPrincipal'到了System.Security.Principal.IPrincipal'

时间:2016-02-22 12:56:25

标签: c# .net model-view-controller 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.
        }
    }

这是发生错误的最后一行。

  

无法隐式转换类型&#39; SocialMedia.Models.CustomPrincipal&#39;到了System.Security.Principal.IPrincipal&#39;。存在显式转换(您是否错过了演员?)

为什么它不起作用可能是什么问题。?

2 个答案:

答案 0 :(得分:1)

错误很明显,您分配给User属性的实例需要IPrincipal类型的实例,我怀疑您的CustomPrincipal类不是从IPrinicipal继承的界面,那是因为你看到了错误。

答案 1 :(得分:0)

将最后一行更改为:

HttpContext.Current.User = (IPrincipal)newUser;

修改

确保ICustomPrincipal扩展了IPrincipal界面。