Tuesday, September 9, 2008

The "cookie" property of mshtml.IHtmlDocument2 does not work anymore

In one of our applications we host the Internet Explorer ActiveX control in a window and manually create parameters for navigation (including the body and http headers). To correctly inject the ASP.NET session id cookie into such requests (the page we navigate to comes from the ASP.NET server) we have to be able to somehow inject the ASP.NET_SessionId cookie into the navigation context.

The application was written two (or three) years ago, and we've been injecting the cookie using the cookie property of the mshtml.IHtmlDocument2 interface.

/* we've retrieving the reference to the document */
mshtml.IHtmlDocument2 doc = ...; 
/* and we've been setting the aspnet session id cookie */
doc.cookie = ...;

This worked like a charm, up to this year - the application is heavily used but only in september (it's responsible for gathering and processing some data available in september and then the data is passed to another appliaction) and this year we've been surprised to see that the cookie property does not work (at least in Internet Explorer 7). Both accessors (set and get) seem to have no effect and you always get the null value from the getter.

Pretty annoying. I guess it's somehow related to security issues but surely it broke the backward compatibility, at least for us.

The solution is to use another method which can inject cookies into the http processing chain:

/* injects cookies into the http processing for
   current process */
public static extern bool InternetSetCookie( 
    string Url,
    string CookieName,
    string CookieData
    /* first inject the cookie */
        "theaspnetcookievalue_nomatterhowyougetit" );
    /* then navigate */
    webBrowser1.Navigate( "url" );
    /* the cookie is correctly set for the navigation.
       although you STILL cannot see it using mshtml.IHtmlDocument2.cookie,
       the http debugger reveals that it's really there 


Jigar said...

Hi I am also facing same problem. What is the other way of getting cookies value instead of using mshtml.IHtmlDocument2?

Wiktor Zychla said...

did you try the InternetGetCookie function?

Jigar said...

Hi Wiktor,
Thanks for reply. I tried the InternetGetCookie function but it also returned same values. Actually I get some cookie values but not all. Later on, I came to know that httponly cookies are not accessible from client application. Is there any way in which we can retrieve httponly cookies also?

Wiktor Zychla said...

Jigar, if there's a better way I would like to learn it.

Nevertheless, you can make an additional request to the webserver using the HttpWebRequest class and then manually parse the response stream to find the http cookie header.

Unknown said...

when i type cookies in 'run'program then "cookies is not accessible"raised.how can i set path for cookies