3

in my app. there's a log in mechanism which save a cookie with the info of the user who just logged in

     private void CreateCookie(LoginEventArgs args)
     {
         HttpCookie cookie = new HttpCookie("user");
         cookie.Values["name"] = args.User_Name;
         cookie.Values["id"] = args.ID;
         cookie.Expires = DateTime.Now.AddDays(1);            
         Response.Cookies.Add(cookie);
     }

on my master page load i perform a check to see if this cookie exists or not :

   HttpCookie cookie = Request.Cookies["user"] ;
   if( (cookie != null) && (cookie.Value != ""))  
   {
        if (Session["user"] == null)
            Login_Passed(this, new LoginEventArgs(cookie.Values["name"].ToString(), int.Parse(cookie.Values["id"])));
   }

now if i Log in ( Create A cookie ) , close the browser , and run my app. again the cookie exists it's values are correct and the user is "automatically" logged in .

if i first redirect to a different content page from the start up content page the cookies values are also intact ,

the problem is when i redirect back to a different content page a second time, the master page loads , makes the check the cookie exists but the values are deleted ...

any ideas on why this happens ?

btw maybe the way i log out could be the reason for this problem :

when i log-out i create a cookie with the same name that expires 1 day ago .

   private void Remove_Cookie()
   {
        HttpCookie cookie = new HttpCookie("user");
        cookie.Expires = DateTime.Now.AddDays(-1);
        Response.Cookies.Add(cookie); 
   }

in the case iv'e described i don't log-out formally , i just end my app , so this shouldn't have any effect .

eran otzap
  • 12,293
  • 20
  • 84
  • 139
  • Are you testing this on your developer IIS? – Rumplin Sep 22 '11 at 06:31
  • i don't even know what that is.. – eran otzap Sep 22 '11 at 06:33
  • Well that is the IIS server that runs when you debug in Visual Studio. Because by default it adds a random port to that server, and your cookie may depend on that localhost:port address, try to set a fixed port in your web project. – Rumplin Sep 22 '11 at 06:36
  • the problem still exists – eran otzap Sep 22 '11 at 06:45
  • i think the problem is that when i redirect again , a different request is executed and the last request's cookies are deleted , any ideas how to save cookies between requests ? with out re-creating the cookie on every Page_Load of the master page. – eran otzap Sep 22 '11 at 07:16

4 Answers4

18

o'k , the problem was unthinkable
special thanks to Peter Bromberg

http://www.eggheadcafe.com/tutorials/aspnet/198ce250-59da-4388-89e5-fce33d725aa7/aspnet-cookies-faq.aspx

in the section of the Article " The Disappearing Cookie "

the author states that if you have a watch on Response.Cookies["cookie_name"] the browser creates a new empty cookie that overrides your cookie .

i used such a watch which made my cookie loose it's values ,and when i took it off the cookie kept its values.

the moral is DON't WATCH Response.Cookies[" "] also i read in some other post that if you check

 if( Response.Cookies["cookie_name"] != null    )  

for example it also gets overridden.

eran otzap
  • 12,293
  • 20
  • 84
  • 139
8

To reiterate and build upon what has already been stated (yes, I know this is a 4 year old question) I have found it best to build a utility to handle this - mostly because I want to check that specific cookie often.

This will not touch the Response but only read from the Request.

    public static HttpCookie GetCookie(string cookieName)
    {
        HttpCookie rqstCookie = HttpContext.Current.Request.Cookies.Get(cookieName);
        /*** NOTE: it will not be on the Response!
         *   this will trigger the error noted in the original question and
         *   create a new, empty cookie which overrides it
         *   
            HttpCookie respCookie = HttpContext.Current.Response.Cookies.Get(cookieName);
         * 
         */
        if (rqstCookie != null && !String.IsNullOrEmpty(rqstCookie.Value))
        {
            // is found on the Request
            return rqstCookie;
        }
        else
        {
            return null;
        }
    }

rule-of-thumb

Always read from the Request and write to the Response.

Thanks eran! this post was exactly what I needed

rwcorbett
  • 473
  • 5
  • 12
  • 1
    Very useful! For anyone using C# 6.0 Onwards. The following line can be used instead of the entire if/else statement. `return !string.IsNullOrEmpty(rqstCookie?.Value) ? rqstCookie : null;` – Daniel Filipe May 11 '18 at 09:18
0

Use the following approach to get a value from cookies:

public string GetValueFromCookies(HttpCookieCollection cookies)
{
    if (cookies == null)
    {
        throw new ArgumentNullException(nameof(cookies));
    }

    // check the existence of key in the list first
    if (Array.IndexOf(cookies.AllKeys, key) < 0)
    {
        return null;
    }

    // because the following line adds a cookie with empty value if it's not there
    return cookies[key].Value;
}
Alex Valchuk
  • 623
  • 6
  • 8
0

try the following:

  • If you are developing on your local machine, put your app on some free web page, so there will be no 'special treatment' because you're in the local host.
  • If you already are on a web-server, and if the re-directions are between tow different domains, you may want to search google for 'same origin policy' or read this: http://en.wikipedia.org/wiki/Same_origin_policy (the document talks about javascript, but its true also for cookies).
Ramzi Khahil
  • 4,932
  • 4
  • 35
  • 69
  • i am working on my local machine , excuse my ignorance but what do you mean by "free web page" – eran otzap Sep 22 '11 at 07:25
  • I mean that you don't have to pay for hosting. Because its a waste of money to pay for webhosting while you are developing. (Unfortunately I don't know where to find that) Another thing you may try is a different browser. – Ramzi Khahil Sep 23 '11 at 10:08
  • the question was is the cookie suppose to stay alive between requests or not , when i redirect again its a different request , but still the cookie is stored on my machine so its suppose to be sent again even if there is another request , ill try it on a different browser and let you know – eran otzap Sep 23 '11 at 20:23
  • same problem with different browser – eran otzap Sep 23 '11 at 20:30