开发者

WCF REST WebHttpBinding cookie handling

The problem is WCF client doesn't respect server cookie (doesn't set it on the next request). Here is how I create the client:

WebChannelFactory<IPostService> factory = new WebChannelFactory<IPostService>(
    new WebHttpBinding() {AllowCookies = true},
    new Uri("http://10.6.90.45:8081"));

_proxy = factory.CreateChannel();

Settings AllowCookies to false has no effect too.

What I did for now is wrote a simple IClientMessageInspector to persist the server cookie between requests, but I really don't want to do this, there should be a way to handle cookie in a standard way.

The custom inspector I'm using now, which is working as expected, but I'm looking for a "clean" solution:

  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;
            }
         }
      }
   }


How to add cookie on a HttpTransportBindingElement see this page it has complete answer to your question


Don't know if this was "fixed" in more recent .NET version (I'm on 4.5), or if the OP had other problems that were keeping this from working, but the allowCookies setting DOES work for this purpose.

It is working for me.... I also have "aspnetcompatabilitymode" set on the server.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜