2008-10-28 50 views

回答

1

您的代碼實際上是否需要通過ASP.NET登錄的用戶,還是隻需要一個CurrentPrincipal?我不認爲你需要以編程方式登錄到您的網站。您可以創建一個GenericPrincipal,設置您需要的屬性並將其附加到,例如Thread.CurrentPrincipal或模擬的HttpContext。如果您的代碼實際上需要RolePrincipal或其他東西,那麼我會更改代碼以減少耦合到ASP.NET成員身份。

+0

我需要調用Membership.GetUser()返回當前登錄的用戶。 – ddc0660 2008-10-30 16:10:30

0

使用您的會員供應商,您可以使用Membership.ValidateUser驗證用戶。然後,您可以使用FormsAuthentication.SetAuthCookie來設置身份驗證Cookie。只要你有一個cookie容器,這應該允許你登錄一個用戶。

2

我發現創建一個一次性類來處理設置和重置Thread.CurrentPrincipal是最方便的。

public class TemporaryPrincipal : IDisposable { 
     private readonly IPrincipal _cache; 

     public TemporaryPrincipal(IPrincipal tempPrincipal) { 
      _cache = Thread.CurrentPrincipal; 
      Thread.CurrentPrincipal = tempPrincipal; 
     } 

     public void Dispose() { 
      Thread.CurrentPrincipal = _cache; 
     } 
    } 

在測試方法中,您只是一個using語句這樣的包裝您的來電:

using (new TemporaryPrincipal(new AnonymousUserPrincipal())) { 
    ClassUnderTest.MethodUnderTest(); 
} 
13
if(Membership.ValidateUser("user1",[email protected])) 
     { 
      FormsAuthentication.SetAuthCookie("user1",true); 
} 
相關問題