gpt4 book ai didi

WCF -> ASMX 和 Cookie

转载 作者:行者123 更新时间:2023-12-05 01:28:37 25 4
gpt4 key购买 nike

我有一个 Web 应用程序,它通过 WCF 客户端与 WCF 服务通信。在调用我的代码时,已发出身份验证 cookie,并且我依赖于需要这些身份验证 cookie 的 ASMX 服务。

我需要通过 WCF 客户端将 cookie 从 Web 应用程序传递到 WCF 服务,再传递到 ASMX 服务。

有什么想法吗?看起来我最好的选择可能是将 allowCookies 设置为 false,解析出 cookie header ,尝试在 WCF 服务上重新创建它们,然后将它们附加到 SOAP 请求。

注意:我查看了this article ,这似乎很接近但不太适用于这个问题。在链接方案中,ASMX 服务正在创建 cookie,该 cookie 必须由同一 WCF 客户端持久保存到后续 ASMX 服务。

最佳答案

好的,所以有两件主要的事情需要发生:

  1. 从 Web 应用上下文获取 cookie 到 WCF 服务
  2. 从WCF服务获取cookie到ASMX服务

注意:因为您没有指定,所以我将假设您在 WCF 服务中使用 WCF 客户端与 ASMX 服务对话.如果不是这种情况,请告诉我,我会相应地修改这篇文章。

第 1 步:

我建议写一个 IClientMessageInspector您使用 IEndpointBehavior 绑定(bind)到您的客户端端点.在您执行 IClientMessageInspector::BeforeSendRequest 的过程中您基本上是从当前 HttpContext::Request::Cookies 集合中读取 cookie,并将该值附加为消息 header 。这看起来有点像这样:

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

如果您使用此消息检查器配置端点,每个逻辑请求都会自动将 cookie 值作为 header 传递给您的 WCF 服务。现在,由于您的 WCF 服务实际上并不关心 header 本身,它基本上可以忽略它。事实上,如果您只执行了这一步,您现在应该能够运行所有代码并且不会遇到任何差异。

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

您需要再次使用 IEndpointBehavior 将其绑定(bind)到您的 ASMX 服务的端点并且您发出的每个逻辑请求都会自动传递 cookie。

关于WCF -> ASMX 和 Cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1556218/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com