2013-02-27 97 views
0

我使用WCF自定義驗證與HTTPS(.NET 4.5)。成功驗證返回客戶對象,我想稍後使用。目前,我可以用靜態變量來做到這一點,如果可能的話,我願意避免這些變量。我試圖使用在主線程中變爲null的HttpContext。我的理解驗證在不同線程下運行。有沒有什麼辦法可以分享會話信息,而不涉及數據庫或文件共享。請參閱相關主題herehereUserNamePasswordValidator和會話管理

在Authentication.cs

public class CustomValidator : UserNamePasswordValidator 
{ 
     public override void Validate(string userName, string password) 
     { 
     //If User Valid then set Customer object 
     } 
} 

在Service.cs

public class Service 
    { 
     public string SaveData(string XML) 
     { 
     //Need Customer object here. Without it cannot save XML. 
     //HttpContext null here. 
     } 
    } 

回答

0

好吧,這應該更容易。由於UserNamePasswordValidator的工作方式,我需要使用自定義授權將用戶名/密碼傳遞給主線程,並再次從數據庫獲取客戶信息。這是一個額外的數據庫調用,但目前可接受的解決方法。請從Rory Primrose's genius blog entry下載代碼。

1

我可以建議你另一種方法。假設WCF服務以ASP.Net兼容模式運行,並且您將客戶對象保存到會話存儲。創建一個類如AppContext

當兩個WCF和ASP.Net管道都執行的代碼會是這個樣子

public class AppContext { 
public Customer CurrentCustomer { 
    get { 
    Customer cachedCustomerDetails = HttpContext.Current.Session[CUSTOMERSESSIONKEY] as Customer; 
     if (cachedCustomerDetails != null) 
     { 
      return cachedCustomerDetails; 
     } 
     else 
     { 
      lock (lockObject) 
      { 
       if (HttpContext.Current.Session[CUSTOMERSESSIONKEY] != null)  //Thread double entry safeguard 
       { 
        return HttpContext.Current.Session[CUSTOMERSESSIONKEY] as Customer; 
       } 

       Customer CustomerDetails = ;//Load customer details based on Logged in user using HttpContext.Current.User.Identity.Name 
       if (CustomerDetails != null) 
       { 
        HttpContext.Current.Session[CUSTOMERSESSIONKEY] = CustomerDetails; 
       } 

       return CustomerDetails; 
      } 
     } 
    } 
} 

這裏的基本思路是做數據的延遲加載,並HttpContext的可用。

希望它有幫助。

+0

感謝您的回覆。我已經嘗試過這個解決方案。當您從驗證轉到保存數據方法時,HttpContext超出範圍。 FYI,Validate中的OperationContext爲null。 – 2013-02-27 17:42:33

+0

好的,而不是HttpContext使用OperationContext。您可以從OperationContext.Current.ServiceSecurityContext.PrimaryIdentity.Name獲取用戶名。在Authenitcate期間,您不會將客戶添加到會話中。您首次請求客戶數據時將其添加到會話中。此時用戶已通過身份驗證,並且會話可用於您的服務。 – Chandermani 2013-02-28 07:09:10

+1

Validate中的OperationContext爲null。 UserNamePasswordValidator在不同的上下文/線程中運行。 – 2013-03-05 23:56:29