A blog about Erik, Cats, Newts, Owls, Crafts, Cars, Toys and Microsoft! I liked Erik before he was popular.


Cookie Aware WebClient for WP7

If you are using Silverlight in WP7, you will most likely be connecting to web services over the wire. Silverlight for WP7 does not contain every single function of .Net you’d expect. There are a few synchronous calls missing. So we have to look at different ways to make call in the background. Webclient is perfect for this because we can hit a webpage/service, get back a string representation of the http response and parse it with LINQ for our data. It will return a simple string, so XML and JSON are both easily worked with.

One issue that arises from using the WebClient is the lack of cookie support. You have to manage your session state manually if you plan on using something like WebClient. You have to make sure you catch the cookie from a HttpRequest and then store it somewhere and then pass it into the WebClient request….HASSLE.

To solve this, just make a simple cookie aware webclient of your own.

    public class CookieAwareClient: WebClient
        public CookieAwareClient()
            : base()
        private CookieContainer m_container = new CookieContainer();
        protected override WebRequest GetWebRequest(Uri address)
            WebRequest request = base.GetWebRequest(address);
            if (request is HttpWebRequest)
                (request as HttpWebRequest).CookieContainer = m_container;
            return request;

This code will enable a new webclient that is security safe for WP7 silverlight and has the ability to store cookies. Once this is built just call your normal download event. The security declaration is required for WP7, you’ll get an exception otherwise.

CookieAwareClient cookieClient = new CookieAwareClient;

cookieClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(cookieAttempt_DownloadStringCompleted);

cookieClient.DownloadStringAsync(new Uri(“http://yourlogin.com/login?username&pass));

Just keep that object alive and reuse it to call other parts of the webpage and you’re good.


  1. firebellys posted this