Im trying to make a persistent cookie using C# 4.0 and this code:
HttpCookie AssoCookie = new HttpCookie("AssociateCode", AssociateCode);
AssoCookie.Expires = DateTime.Now.AddMonths(6);
HttpContext.Current.Response.Cookies.Add(AssoCookie);
Unfortunately, it doesn't work and the cookie is session expiring. If I use Web Developer plugin in Firefox to check it I can see this info:
Name AssociateCode
Value test
Host localhost
Path /
Secure No
Expires At End Of Session
The cookie I'm doing as a test its just created on there, noone else manages it or edits it so it cannot be overwritten. I have nothing set in webconfig to set cookies expiration (anyway this should override that) and if I set some cookies expiration time it doesnt work.
I'm a bit lost now, every manual, tutorial, blog, whatever I check says you just have to set the Expiration date, Ive debugged, Ive checked that it really has that value when created and at the end of Page_PreRender but it just expires with session whatever I do.
Any ideas?
Im using Firefox 9.0.1 btw.
Update
Using Firebug plugin in Firefox to check response headers I get this:
Response Headersview source
Cache-Control private
Connection Close
Content-Length 21322
Content-Type text/html; charset=utf-8
Date Mon, 23 Jan 2012 16:47:08 GMT
Server ASP.NET Development Server/10.0.0.0
Set-Cookie AssociateCode=test; expires=Mon, 23-Jul-2012 16:09:04 GMT; path=/
X-AspNet-Version 4.0.30319
And using Fiddler I get this:
HTTP/1.1 200 OK
Cache-Control: private
Content-Type: text/html; charset=utf-8
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
Set-Cookie: AssociateCode=; expires=Mon, 23-Jul-2012 16:27:29 GMT; path=/
X-Powered-By: ASP.NET
Date: Mon, 23 Jan 2012 17:27:29 GMT
Content-Length: 21313
** Update 2 ** Im checking that the Cookie doesnt exist just checking between my Firefox's cookies, but, in case you want to see how I get it later in code (not necessary since it not on there anyway):
try {
AssociateCode = HttpContext.Current.Request.Cookies.Get("AssociateCode").Value;
} catch { }
Just to follow up with my comment:
The info from fiddler and firefox's tools show that you are sending the correct information to create the cookie.
This leads me to believe that you are incorrectly testing it's existence.
When testing if a cookie is passed to your application you should use the Request.Cookies
container to see if it's there. (note that it is REQUEST not RESPONSE).
If you test by using something like:
if (Response.Cookies["mycookie"] == null) { .. }
Then this will cause a new cookie in the response object to be created that is blank.
To sum up: the Request object will contain everything sent from the browser. The Response object is everything you are sending to the browser.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With