我最终使用了本教程中的方法。我将相关信息作为键值对添加到 cookie 中,并在服务实现中读取。我使用的不是服务参考ChannelFactory
,但基本上主要思想与教程中的相同。
我的BeforeSendRequest
方法是:
public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request,
System.ServiceModel.IClientChannel channel)
{
HttpRequestMessageProperty httpRequestMessage;
object httpRequestMessageObject;
if (request.Properties.TryGetValue(HttpRequestMessageProperty.Name
, out httpRequestMessageObject))
{
httpRequestMessage = httpRequestMessageObject as HttpRequestMessageProperty;
if (string.IsNullOrEmpty(httpRequestMessage.Headers["Cookie"]))
{
httpRequestMessage.Headers["Cookie"] = cookie;
}
}
else
{
httpRequestMessage = new HttpRequestMessageProperty();
httpRequestMessage.Headers.Add("Cookie", cookie);
request.Properties.Add(HttpRequestMessageProperty.Name
, httpRequestMessage);
}
return null;
}
绑定设置为:
<basicHttpBinding>
<binding name="basicHttp" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferPoolSize="20000000" maxBufferSize="20000000" maxReceivedMessageSize="20000000"
textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true"
messageEncoding="Text">
<readerQuotas maxDepth="32" maxStringContentLength="200000000" maxArrayLength="200000000"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
</basicHttpBinding>
在我需要的客户端应用程序中(在web.config
system.serviceModel
):
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
并在服务实现类注解中:
[AspNetCompatibilityRequirements(RequirementsMode =
AspNetCompatibilityRequirementsMode.Required)]
public class MyService : IMyService {
// ...
}
对于服务调用,我使用了一个包装器对象,它实现了在创建通道之前IDisposable
进行适当处理并添加到的情况。EndpointBehaior
ChannelFactory
_factory = new ChannelFactory<T>( );
_factory.Endpoint.Behaviors.Add(new CookieEndpointBehavior(cookieStr));
_channel = _factory.CreateChannel();
我正在使用服务包装类,一旦超出范围using block
就会调用。Dispose