【发布时间】:2011-07-20 14:56:17
【问题描述】:
问题是 WCF 客户端不尊重服务器 cookie(不在下一个请求中设置它)。以下是我创建客户端的方式:
WebChannelFactory<IPostService> factory = new WebChannelFactory<IPostService>(
new WebHttpBinding() {AllowCookies = true},
new Uri("http://10.6.90.45:8081"));
_proxy = factory.CreateChannel();
将 AllowCookies 设置为 false 也没有效果。
我现在所做的是写了一个简单的 IClientMessageInspector 来在请求之间持久化服务器 cookie,但我真的不想这样做,应该有一种方法可以以标准方式处理 cookie。
我现在使用的自定义检查器按预期工作,但我正在寻找一个“干净”的解决方案:
public class CookieInspector : IClientMessageInspector
{
private string _cookie;
public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
if(_cookie != null && request.Properties.ContainsKey("httpRequest"))
{
HttpRequestMessageProperty httpRequest = request.Properties["httpRequest"] as HttpRequestMessageProperty;
if(httpRequest != null)
{
httpRequest.Headers["Cookie"] = _cookie;
}
}
return null;
}
public void AfterReceiveReply(ref Message reply, object correlationState)
{
if (reply.Properties.ContainsKey("httpResponse"))
{
HttpResponseMessageProperty httpResponse = reply.Properties["httpResponse"] as HttpResponseMessageProperty;
if(httpResponse != null)
{
string cookie = httpResponse.Headers.Get("Set-Cookie");
if (cookie != null) _cookie = cookie;
}
}
}
}
【问题讨论】:
标签: wcf