Wcf UserNamePasswordValidator和会话管理
我将WCF自定义验证程序与HTTPS(.NET 4.5)一起使用。Validate on success返回我稍后要使用的Customer对象。目前,我可以使用静态变量,如果可能的话,我喜欢避免使用静态变量。我尝试使用HttpContext,它在主线程中变为null。我的理解在不同的线程下运行。是否有任何方法可以在不涉及数据库或文件共享的情况下共享会话信息。请参阅相关线程和 在Authentication.cs中Wcf UserNamePasswordValidator和会话管理,wcf,ws-security,Wcf,Ws Security,我将WCF自定义验证程序与HTTPS(.NET 4.5)一起使用。Validate on success返回我稍后要使用的Customer对象。目前,我可以使用静态变量,如果可能的话,我喜欢避免使用静态变量。我尝试使用HttpContext,它在主线程中变为null。我的理解在不同的线程下运行。是否有任何方法可以在不涉及数据库或文件共享的情况下共享会话信息。请参阅相关线程和 在Authentication.cs中 public class CustomValidator : UserNamePa
public class CustomValidator : UserNamePasswordValidator
{
public override void Validate(string userName, string password)
{
//If User Valid then set Customer object
}
}
在职
public class Service
{
public string SaveData(string XML)
{
//Need Customer object here. Without it cannot save XML.
//HttpContext null here.
}
}
我可以向你推荐一种替代方法。假设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可用时,延迟加载数据
希望能有帮助。好吧,这应该更容易些。由于UserNamePasswordValidator的工作方式,我需要使用自定义授权将用户名/密码传递给主线程,并再次从数据库中获取客户信息。这是一个额外的DB调用,但目前可以接受。请从下载代码 谢谢你的回复。我已经试过这个方法了。从Validate转到SaveData方法时,HttpContext超出范围。仅供参考,验证中的OperationContext也为null。确定,使用OperationContext代替HttpContext。您可以从OperationContext.Current.ServiceSecurityContext.PrimaryIdentity.Name获取用户名。在Authenitcate期间,您不会将客户添加到会话中。首次请求客户数据时,将其添加到会话中。此时,用户已通过身份验证,会话可用于您的服务。验证中的OperationContext为null。UserNamePasswordValidator在不同的上下文/线程中运行。