UserNamePasswordValidator和会话管理

时间:2013-02-27 03:22:15

标签: wcf ws-security

我正在使用带有HTTPS(.NET 4.5)的WCF自定义验证程序。成功时验证返回我想稍后使用的Customer对象。目前我能够使用静态变量,如果可能的话我想避免使用。我试图使用HttpContext,它在主线程中变为null。我的理解验证在不同的线程下运行。有没有办法在不涉及DB或文件共享的情况下共享会话信息。请参阅相关主题herehere

在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.
      }
  }  

2 个答案:

答案 0 :(得分:1)

我可以建议你另一种方法。假设WCF服务在ASP.Net兼容模式下运行,并且您将客户对象保存到会话存储。创建一个类AppContext

代码看起来像这样

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;
            }
        }
  }
}

这里的基本思想是在WCF和ASP.Net管道都已执行且HTTPContext可用时进行延迟加载数据。

希望它有所帮助。

答案 1 :(得分:0)

好吧,这本来应该更容易。由于UserNamePasswordValidator的工作方式,我需要使用自定义授权将UserName / Password传递给主线程,并从数据库中再次获取客户信息。这是一个额外的数据库调用,但现在可接受的解决方法。请从Rory Primrose's genius blog entry下载代码。

相关问题