Posted by Ryan Grange on February 6, 2008
This entry was posted on February 6, 2008 at 4:50 am and is filed under Articles.
Tagged: ASP, ASP.Net. You can follow any responses to this entry through the RSS 2.0 feed.
You can leave a response, or trackback from your own site.
Wayne said
So how exactly is that done on the asp.net side?
Ryan Grange said
If you are working with an .aspx.vb or .aspx.cs file, the longhand method would be…
string cookieValue = HttpUtility.UrlDecode( Request.Cookies[ HttpUtility.UrlEncode( "Cookie Name" ) ] );
When setting a cookie value in the Request.Cookies collection, be sure to HttpUtility.UrlEncode both the name of the cookie and the value as well.
Wayne said
Thanks for the reply. Let me ask you this, I’m trying to read the cookie in ASP.NET from ASP then write it in ASP.NET hoping this will work. What I’m doing is using cookie variables in a JavaScript menu application called from the ASP or ASP.NET pages. Currently when it hits the ASP.NET application page the cookie value becomes null, so the JavaAcript isn’t capable of reading the cookie apparently when invoked by ASP.NET.
My thought is to read the cookie in ASP.NET, then write it in ASP.NET, then call the JavaScript routine hoping that now it will read the cookie correctly.
To that point, since I know almost nothing about .NET yet, what is the code to write the cookie again? I would read it with your snippet above, then immediately write it with the same cookie name. Will JavaScript read it correctly?
Wayne said
Here’s an interesting observation. In the above scenario firefox works fine and maintain state going from asp pages to asp.net pages and back again.
IE 6 and 7 do not, as soon as I hit the asp.net page it loses the cookie.
What’s up with that?
Ryan Grange said
Assuming the pages are hosted in a test environment, you could enable the trace output on the page giving you issues with cookies. In the declaration add the property Trace=”true”. You should see the cookies being received by the page in the results.
Cookies you write can be read out easily with the web developer extension for Firefox. With IE, there may be some kind of add-on for that, or you may want to make a shortcut to your cookies folder so you can look at the text it stored directly.
Also, bear in mind that the code I posted above was meant as a rough idea. You’ll also need to test for the existence of the cookie before retrieving it or you could trigger a null reference exception.
Bhuvana said
The below javascript can be used to retrieve cookie values in any web page.
The below script can be added to “Links” list(name it ‘Show Cookies’) in IE. Then, you can just click ‘Show Cookies’ from Links tab and drag & drop in any web page.
javascript:var aCookie=document.cookie.split(“; “);for(var i = 0; i < aCookie.length; i++){document.write(unescape(aCookie[i]) + “”);}