简体   繁体   中英

Cannot find the cookies in asp.net c#

I am creating a web page with .net 2.0 and I want to check if it is the first time visit for the user.

I am using the code block in pageload():

String CookieName = "Cookie";
String CookieValue = "TEST";
if (Request.Cookies[CookieName] != null)
{
Label3.Visible = true;
if (Request.Cookies[CookieName].Value == CookieValue)
{
    Label3.Text = "Cookie already exists: " + Request.Cookies[CookieName].Value.ToString();
}
else 
    Label3.Text = "Cookie var içerisinde: " + Request.Cookies[CookieName].Value.ToString();
}
else
{
Label3.Visible = true;
HttpCookie MyCookie=new HttpCookie(CookieName,CookieValue);
Response.Cookies.Add(MyCookie);
Label3.Text = "Cookie created. " + Request.Cookies[CookieName].Value.ToString();
}

Everything seems to be working, as I run the code "Label3" becomes "Cookie created. Cookie". And after another postback "Label3" becomes "Cookie already exists. Cookie" as it should be.

But I couldn't find my cookies anywhere in my local harddrive.(even if I didn't end the session)

And after ending session and re-run the code, it starts again with "Cookie created. Cookie" which means it couldn't find the previous cookie.

It is obvious that something is missing. I tried to add expry date and path to the cookie. None of them worked for me.

Thank you in advance.

Cagri

But I couldn't find my cookies anywhere in my local harddrive.(even if I didn't end the session)

If you have Chrome, and why don't you :), use it's built-in Dev tools Ctrl Shift I and select the Resources tab and boom! not just cookies !:

Chrome开发人员工具

If you look above, in the Expires column, you'll see one cookie expires at the end of the browser Session , while the other has a set Date.

The cookies you are creating above are Session (dies after browser close).

If you want to them to be persistent and survive a browser close, define Expires property like so:

Response.Cookies.Add(new HttpCookie(CookieName, "hello persistent") { Expires = DateTime.Now.AddDays(1) });

Hth...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM