【问题标题】:WCF REST WebHttpBinding cookie handlingWCF REST WebHttpBinding cookie 处理
【发布时间】: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


    【解决方案1】:

    不知道这是否在最近的 .NET 版本中“修复”(我在 4.5 上),或者 OP 是否有其他问题使其无法正常工作,但 allowCookies 设置确实适用于此目的.

    它对我有用....我还在服务器上设置了“aspnetcompatabilitymode”。

      <webHttpBinding>
        <binding name="webHttpEndpointBinding" allowCookies="true">
          <security mode="TransportCredentialOnly">
            <transport clientCredentialType="Windows"/>
          </security>
        </binding>
      </webHttpBinding>
    

    【讨论】:

      【解决方案2】:

      How to add cookie on a HttpTransportBindingElement 看到这个页面它有你的问题的完整答案

      【讨论】:

      • 谢谢,但它并没有说明我不知道的任何内容。您必须编写自己的 IClientMessageDispatcher ,这就是我现在正在使用的。我正在寻找 自动 cookie 管理,就像在 HttpWebRequest 中一样。服务器发送一个cookie,客户端接受cookie,并在下一次请求时将其发送回服务器。普通网页模型,无特殊逻辑。在没有自定义检查器的情况下,这在 WCF 中是否可以实现?
      • 我对 wcf cookie 了解不多。我只是在阅读它。我读了这篇文章megakemp.wordpress.com/2009/02/06/… 可能会解决你的问题
      猜你喜欢
      • 2011-03-15
      • 2012-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-10
      • 2011-07-14
      • 1970-01-01
      相关资源
      最近更新 更多