Building on Custom Cookie Handling

By request I expanded the code in the earlier article on custom cookie handling to show a more interesting sample. This time I illustrated making the initial request and capturing a cookie rather than echoing a cookie that the client already had. This sample is specifically written to not use proxies or any of the web programming features so that you can see exactly what goes on under the covers. I threw in a demonstration of CookieContainer for integration but you can use any mechanism you'd like to manage the cookies.

You can run this code against your favorite site that distributes cookies. I picked a random site that advertised having a cookie tester. There's no guarantee that this site will be there tomorrow.

 using System;
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Text;

class CookieTest
{
   static void Main(string[] args)
   {
      string address = "www.tempesttech.com/cookies/cookietest1.asp";
      Binding binding = new CustomBinding(
         new TextMessageEncodingBindingElement(MessageVersion.None, Encoding.UTF8),
         new HttpTransportBindingElement()
      );
      IChannelFactory<IRequestChannel> factory = binding.BuildChannelFactory<IRequestChannel>();
      IRequestChannel channel = null;
      bool success = false;
      try
      {
         factory.Open();
         channel = factory.CreateChannel(new EndpointAddress(address));
         channel.Open();
         Message request = Message.CreateMessage(MessageVersion.None, null);
         HttpRequestMessageProperty requestProperty = new HttpRequestMessageProperty();
         requestProperty.Method = "GET";
         requestProperty.SuppressEntityBody = true;
         request.Properties[HttpRequestMessageProperty.Name] = requestProperty;
         Message response = channel.Request(request);
         request.Close();
         HttpResponseMessageProperty responseProperty =
            response.Properties[HttpResponseMessageProperty.Name] as HttpResponseMessageProperty;
         CookieContainer container = new CookieContainer();
         container.SetCookies(new Uri(address), responseProperty.Headers[HttpResponseHeader.SetCookie]);
         response.Close();
         foreach (Cookie cookie in container.GetCookies(new Uri(address)))
         {
            Console.WriteLine(cookie);
         }
         channel.Close();
         factory.Close();
         success = true;
      }
      catch (TimeoutException e)
      {
         Console.WriteLine(e);
      }
      catch (CommunicationException e)
      {
         Console.WriteLine(e);
      }
      finally
      {
         if (!success)
         {
            if (channel != null)
            {
               channel.Abort();
            }
            factory.Abort();
         }
      }
      Console.ReadLine();
   }
}

Next time: Producing Typed Messages