2011-04-28 29 views
4

我使用Application_PostAuthenticateRequest事件在Global.asax中創建自定義IPrincipal對象在哪裏創建自定義IPrincipal對象?

void Application_PostAuthenticateRequest(object sender, EventArgs args) 
{ 
    if (Context.User.Identity.IsAuthenticated == true) 
     if (Context.User.Identity.AuthenticationType == "Forms") 
     {     
       Context.User = new CustomPrincipal(Context.User); 
       Thread.CurrentPrincipal = Context.User; 
     }     
} 

在我的應用程序,我想獲得有關登錄的用戶一些信息來使用。我認爲這將被稱爲一次,當用戶身份驗證,但我注意到,它被調用每個頁面請求幾次相同的登錄用戶。我發現即使是從AppThemes請求圖片也會調用這種方法!

我應該在哪裏創建該對象,以避免爲每個用戶多次調用此方法?

回答

5

我發現一個回答我的問題。

在loggin_in情況下,我應該保存身份驗證cookie(我可以存儲後來我需要在我的UserData屬性customPrincipal所有信息),並在Application_PostAuthenticateRequest我應該從該cookie創建CustomPrincipal。 這樣,這個事件觸發每一個請求,但我不打數據庫 - 我從cookie讀取數據。

我跟着http://www.ondotnet.com/pub/a/dotnet/2004/02/02/effectiveformsauth.html

在我的情況的代碼是:

void Application_PostAuthenticateRequest(object sender, EventArgs args) 
    { 
     HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName]; 
     if (authCookie == null) 
      return; 
     FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); 
     string[] customData = authTicket.UserData.Split(new Char[] { '|' }); 

     if (Context.User.Identity.IsAuthenticated == true) 
     { 
      if (Context.User.Identity.AuthenticationType == "Forms") 
      { 
       Context.User = new CustomPrincipal(customData, Context.User); 
       Thread.CurrentPrincipal = Context.User; 
      } 
     } 
} 
2

Context.User不跨請求保存新主體;您必須在每個請求上創建自定義委託人。所以最好在這裏留下這段代碼。否則,它將恢復到FormsPrincipal或WindowsPrincipal,具體取決於應用程序身份驗證模式。

HTH,

布賴恩