Alverant
Alverant

Reputation: 229

How do Cookies Work in ASP.NET?

The website where I work is made up of several projects (written in several languages). Right now we have to use some awkward code in query strings and session variables to keep a person logged in when they go from project to project. Since cookies are domain specific we're trying to convert to them since they can be set in one project using one language yet be accessed by a different project (on the same domain) using a different language.

However I am having problems changing the value of a cookie and deleting them. Or to be more specific, I'm having trouble having any changes I make to a cookie stick.

For example in my logout code:

if (Request.Cookies["thisuserlogin"] != null)
{
    HttpCookie myCookie = new HttpCookie("thisuserlogin");
    myCookie.Value = String.Empty;
    myCookie.Expires = DateTime.Now.AddDays(-1d);
    Response.Cookies.Add(myCookie);
    Response.Cookies.Set(myCookie);
    litTest.Text = myCookie.Expires.ToString() + "<br />" + Request.Cookies["thisuserlogin"].Expires.ToString();
}

I wind up with one line being yesterday and the next line being 1/1/0001 12:00:00 even though they SHOULD be the same cookie. So why is it that even though the cookie was set, it's value did not change? Is there a way to force the user's computer to update a cookie's value, including deletion?

Thank you very much. PS Any URLs you can provide to give an easy-to-understand primer for cookies would be appreciated.

Upvotes: 7

Views: 3472

Answers (2)

NickSuperb
NickSuperb

Reputation: 1204

http://msdn.microsoft.com/en-us/library/ms178194(v=vs.100).aspx

if (Request.Cookies["thisuserlogin"] != null)
{
    HttpCookie byeCookie = new HttpCookie("thisuserlogin");
    byeCookie.Expires = DateTime.Now.AddDays(-1);
    Response.Cookies.Add(byeCookie);

    // Update Client
    Response.Redirect(Request.RawUrl);
}

Upvotes: 1

Joshua
Joshua

Reputation: 8212

You should use a tool like Fiddler on the client side to capture all of the data going back and forth. This will help you see that your cookie should be set with a date in the past (and missing from the next request too).

As for your textbox output, you're listing the cookie you created expire time and the expire time of the request cookie, which doesn't have one. If you were to look at the response cookie instead, you should see the date being set. Also, the call to Response.Cookies.Set is unnecessary. Response.Cookies.Add should be all you need.

Upvotes: 0

Related Questions