2016-02-22 49 views
1

我已按照此guide向IPrincipal添加自定義特性。無法將類型'CustomPrincipal'轉換爲'System.Security.Principal.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?)

可能是爲什麼它不起作用的問題。

+1

如何聲明'CustomPrincipal'類? – Sakura

回答

1

的錯誤是很清楚,你是分配給User財產的情況下,需要IPrincipal型的情況下,我懷疑你的CustomPrincipal類不是從IPrinicipal接口繼承,那是因爲你所看到的錯誤。

0

更改最後一行:

HttpContext.Current.User = (IPrincipal)newUser; 

編輯

確保ICustomPrincipal擴展IPrincipal接口。

+0

引發錯誤: 'SocialMedia.Models.CustomPrincipal'類型的對象無法轉換爲類型'System.Security.Principal.IPrincipal' –

+0

@CarstenLøvboAndersen,那麼您的'CustomPrincipal'實施或您的' ICustomPrincipal'接口。添加到您的問題pelase。 –

相關問題