さて、発生する必要がある2つの主なことがあります:
- WebアプリコンテキストからWCFサービスへのCookieを取得します
- WCFサービスからASMXサービスへのCookieを取得します
注:指定しなかったため、WCFサービス内でWCFクライアントを使用してASMXサービスと通信していると想定します。そうでない場合はお知らせください。それに応じてこの投稿を改訂します。
ステップ1:
IEndpointBehaviorを使用してクライアントエンドポイントにバインドするIClientMessageInspectorを作成することをお勧めします。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);
}
このメッセージインスペクターを使用してエンドポイントを構成すると、すべての論理要求が自動的にCookie値をヘッダーとしてWCFサービスに流します。これで、WCFサービスは実際にはヘッダー自体を気にしないため、基本的にはヘッダーを無視できます。実際、この手順のみを実行した場合は、今すぐすべてのコードを実行でき、違いはありません。
ステップ2:
ここで、WCFサービスからASMXサービスに移動するためのCookieが必要です。ここでも、BeforeSendMessageRequestが少し異なることを除いて、IClientMessageInspectorを実装するだけです。
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を使用してこれをASMXサービスのエンドポイントにバインドする必要があり、作成するすべての論理リクエストは自動的にCookieを通過させます。