我有一个通过WCF客户端与WCF服务通信的Web应用程序.在调用我的代码时,已经发出了身份验证cookie,并且我依赖于期望这些身份验证cookie的ASMX服务.
我需要将cookie从Web应用程序通过WCF客户端传递到WCF服务到ASMX服务.
有任何想法吗?看起来我最好的选择可能是将allowCookies设置为false,解析出cookie头,尝试在WCF服务上重新创建它们,然后将它们附加到SOAP请求中.
注意:我查看了这篇文章,这篇文章似乎很接近但不太适用于这个问题.在链接方案中,ASMX服务正在创建cookie,该cookie必须由同一WCF客户端持久保存到后续ASMX服务.
好的,所以有两个主要的事情需要发生:
注意:因为您没有指定,我将假设您在WCF服务中使用WCF客户端与ASMX服务进行通信.如果不是这样,请告诉我,我会相应修改这篇文章.
步骤1:
我建议编写一个IClientMessageInspector,它使用IEndpointBehavior绑定到客户端端点.在IClientMessageInspector :: BeforeSendRequest的实现中,您基本上从当前的HttpContext :: Request :: Cookies集合中读取cookie,并将该值附加为消息头.这看起来有点像这样:
public void BeforeSendRequest(ref Message request, IClientChannel channel)
{
// Get the cookie from ASP.NET
string cookieValue = HttpContext.Current.Request.Cookies["MyCookieName"].Value;
// Create a header that represents the cookie
MessageHeader myCookieNameHeader = MessageHeader.CreateHeader("MyCookieHeaderName", "urn:my-custom-namespace", cookieValue);
// Add the header to the message
request.Headers.Add(myCookieNameHeader);
}
Run Code Online (Sandbox Code Playgroud)
使用此消息检查器配置端点的每个逻辑请求都将自动将cookie值作为标头传递到WCF服务.现在,由于您的WCF服务实际上并不关心标头本身,因此它基本上可以忽略它.实际上,如果您只执行了此步骤,那么您应该能够立即运行所有代码,而不会遇到任何差异.
第2步:
现在我们需要cookie从WCF服务转到ASMX服务.您需要做的就是实现一个IClientMessageInspector,除了您的BeforeSendMessageRequest将会有所不同:
public void BeforeSendRequest(ref Message request, IClientChannel channel)
{
// Get the cookie value from the custom header we sent in from step #1
string cookieValue = OperationContext.Current.IncomingMessageHeaders.GetHeader<string>("MyCookieHeaderName", "urn:my-custom-namespace");
HttpRequestMessageHeaderProeperty httpRequestMessageHeaderProperty;
MessageProperties outgoingMessageProperties = OperationContext.Current.OutgoingMessageProperties;
// Get the HttpRequestMessageHeaderProperty, if it doesn't already exist we create it now
if(!outgoingMessageProperties.TryGetValue(HttpRequestMessageHeaderProperty.Name, out httpRequestMessageHeaderProperty))
{
httpRequestmessageHeaderProperty = new HttpRequestMessageHeaderProperty();
outgoingMessageProperties.Add(HttpRequestMessageHeaderProperty.Name, httpRequestmessageHeaderProperty);
}
// Set the cookie header to our cookie value (note: sample assumes no other cookies set)
httpRequestmessageHeaderProperty.Headers[HttpRequestHeader.Cookie] = cookieValue;
}
Run Code Online (Sandbox Code Playgroud)
您需要再次使用IEndpointBehavior将此绑定到ASMX服务的端点,并且您所做的每个逻辑请求都将自动传递cookie.