Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HtmlPage.Document.Cookies empty

Firefox shows that there are 3 (non-expired) cookies and I am able to access them in regular ASP.NET aspx.cs code behind. I also have a Silverlight user control on the same page, but when I attempt to access the same cookie it is unable to find any. HtmlPage.Document.Cookies count is 0.

What could I be doing wrong?

I'm using this code:

    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] == key)
                    return keyValue[1];
            }
        }
        return null;
    }

from here

I'm calling it from my view model:

public AQViewModel()
{
    context = new AQContext();
    string cookie = GetCookie("MyCookie");
    .....
}
like image 700
O.O Avatar asked May 23 '11 21:05

O.O


2 Answers

If those cookies are HttpOnly cookies (i.e. containing the HttpOnly flag when created) you won't be able to access them in client scripts such as javascript and Silverlight. For example that's the case with session and forms authentication cookies in ASP.NET.

like image 51
Darin Dimitrov Avatar answered Sep 26 '22 22:09

Darin Dimitrov


A valid solution is to read the cookie from within a WCF service (in my case RIA services) and return it to the Silverlight app

  1. Add System.Web reference to where your wcf classes are
  2. var name = HttpContext.Current.Request.Cookies.Get(cookieName);

this will work for httpOnly, secure, and regular cookies too.

like image 24
O.O Avatar answered Sep 23 '22 22:09

O.O