Silverlight Tip of the Day #18: How to Set Browser Cookies.

Cookies are strings of text that the server can store on the client side. These cookies can then be sent back by the client to the server each time the client accesses that server again. Cookies are commonly used for session tracking, authentication, site preferences and maintaining specific information about users.  For example, items a client stores in a shopping cart can be stored on the client side as cookies so that they can leave the online store and return later to check out.

So, how do we set cookies from within a Silverlight application? To accomplish this we turn again to the HtmlPage.Document object. To use this object you must add a using statement to reference the System.Windows.Browser namespace.

To set a cookie we need to call SetProperty() with a string in the following format: “Key=Value;expires=ExpireDate.”

For example:

 private void SetCookie(string key, string value)
 {
     // Expire in 7 days
     DateTime expireDate = DateTime.Now + TimeSpan.FromDays(7);
  
     string newCookie = key + "=" + value + ";expires=" + expireDate.ToString("R");
     HtmlPage.Document.SetProperty("cookie", newCookie);
 }

Now, to get the cookie we split up and iterate through all the cookies returned through the property HtmlPage.Document.Cookies.

For example:

 private string GetCookie(string key)
 {
     string[] cookies = HtmlPage.Document.Cookies.Split(';');
  
     foreach (string cookie in cookies)
     {
         string [] keyValue = cookie.Split('=');
         if (keyValue.Length == 2)
         {
             if(keyValue[0].ToString() == key)
                 return keyValue[1];
         }
     }
     return null;
 }

For more details on additional properties you can set when creating cookies please see MSDN.

Thank you,

--Mike Snow

 Subscribe in a reader

Comments