2010-05-04 63 views
6

我想知道什麼最好的方法是用我自己的CustomGenericPrincipal替換genericPrincipal。Asp.net:替換GenericPrincipal

目前我有這樣的事情,但我不知道它是否正確。

protected void Application_AuthenticateRequest(Object sender, EventArgs e) 
{ 
    HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName]; 
    if (authCookie != null) 
    { 
     FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); 
     var identity = new CustomIdentity(authTicket); 
     var principal = new CustomPrincipal(identity); 

     Context.User = principal; 
    } 
    else 
    { 
     //Todo: check if this is correct 
     var genericIdentity = new CustomGenericIdentity(); 
     Context.User = new CustomPrincipal(genericIdentity); 
    } 
} 

我需要因爲我需要實現我的ICustomPrincipal接口主要來取代它,因爲我在做與Ninject如下:

Bind<ICustomPrincipal>().ToMethod(x => (ICustomPrincipal)HttpContext.Current.User) 
         .InRequestScope(); 

那麼什麼是更換的GenericPrincipal的最佳方式?

由於提前,

Pickels

回答

5

你缺少一個微妙的細節,該線程。

Context.User = Thread.CurrentPrincipal = new CustomPrincipal.... 

會給你你需要去的地方。

另外我注意到你提到你只需要替換委託人。如果是這種情況,您可以簡單地重新使用已經爲您構建的FormsIdentity,如下所示。

Context.User = Thread.CurrentPrincipal = new CustomPrincipal(Context.User.Identity /*, add roles here if desired*/); 
+0

感謝您的答案和額外的提示。 – Pickels 2010-05-05 11:42:19