我终于找到了一种方法来完成这项工作。对于身份验证,我使用“ WCF 身份验证服务”。验证服务时会尝试设置验证 cookie。我需要从响应中获取此 cookie,并将其添加到对同一台机器上的其他 Web 服务发出的任何其他请求中。执行此操作的代码如下所示:
var authService = new AuthService.AuthenticationServiceClient();
var diveService = new DiveLogService.DiveLogServiceClient();
string cookieHeader = "";
using (OperationContextScope scope = new OperationContextScope(authService.InnerChannel))
{
HttpRequestMessageProperty requestProperty = new HttpRequestMessageProperty();
OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestProperty;
bool isGood = authService.Login("jonas", "jonas", string.Empty, true);
MessageProperties properties = OperationContext.Current.IncomingMessageProperties;
HttpResponseMessageProperty responseProperty = (HttpResponseMessageProperty)properties[HttpResponseMessageProperty.Name];
cookieHeader = responseProperty.Headers[HttpResponseHeader.SetCookie];
}
using (OperationContextScope scope = new OperationContextScope(diveService.InnerChannel))
{
HttpRequestMessageProperty httpRequest = new HttpRequestMessageProperty();
OperationContext.Current.OutgoingMessageProperties.Add(HttpRequestMessageProperty.Name, httpRequest);
httpRequest.Headers.Add(HttpRequestHeader.Cookie, cookieHeader);
var res = diveService.GetDives();
}
如您所见,我有两个服务客户端,一个用于身份验证服务,一个用于我实际要使用的服务。第一个块将调用 Login 方法,并从响应中获取身份验证 cookie。第二个块将在调用“GetDives”服务方法之前将标头添加到请求中。
我对这段代码一点也不满意,我认为更好的选择可能是使用“Web Reference”而不是“Service Reference”并使用 .NET 2.0 堆栈。