locked
Having problems reading a cookie RRS feed

  • Question

  • User-1798522060 posted

    Hi All,

    I have a problem. When trying to read a cookie, I get the following error "Object reference not set to an instance of an object." = it sais that my cookie don't exist. But I know for sure (have detected the cookie name and values in Firefox.

    My code trying to get to the cookie named: Bagperronen_Login:

    public HttpCookie GetCookie(string cookieAddName)
        {
            WebConfigSettings config = new WebConfigSettings();
            string siteTitle = config.SiteTitle.Replace(" ", "_");
    
            if (siteTitle == String.Empty)
            {
                siteTitle = "Bagperronen";
            }
    
            siteTitle = siteTitle + "_" + cookieAddName;
    
            try
            {
                siteTitle = "Bagperronen_Login";
                HttpCookie myCookie = new HttpCookie(siteTitle);
                myCookie = Request.Cookies[siteTitle];
                //HttpCookie myCookie = Request.Cookies["Bagperronen_Login"];
                return myCookie;
            }
            catch
            {
                return null;
            }
    
            
            
        }

    When making a run to curser in that method it gives me above written error. But when looking i firefox I can see the cookie. Can anyone tell me what is wrong in the getCookie method?

    Best regards,
    simsen :-)

    Sunday, May 19, 2013 3:59 PM

Answers

  • User281315223 posted

    If this is actually occuring within the same method (I could be confused) you aren't going to be able to access a cookie that was added to the Response object from the Request until after the Request has actually been made.  (In this case the cookie is never being added to the Response)

    For example : 

    //Create a cookie
    HttpCookie myCookie2 = new HttpCookie("MyCookie");
    
    //The cookie is guaranteed to exist as it was just created above
    if (myCookie2 != null)
    {
        //Add the appropriate properties
        DateTime dtExpiry = DateTime.Now.AddDays(30);
        myCookie2.Expires = dtExpiry;
    }
    else
    {
        //This will never be executed as the if-statement above will never be null
        Response.Cookies.Add(myCookie2);
        DateTime dtExpiry = DateTime.Now.AddDays(30);
        Response.Cookies["MyCookie"].Expires = dtExpiry;
    }
    
    //This will never return a value since the cookie is never added to the Response
    HttpCookie myCookie = Request.Cookies["MyCookie"];

    Instead of checking if the cookie is null, you may want to consider checking the Request to see if it is present as seen below : 

    //Check if the Cookie exists in the Response
    if (Response.Cookies["MyCookie"] != null)
    {
           //If it does - update the expiration
           DateTime dtExpiry = DateTime.Now.AddDays(30);
           Response.Cookies["MyCookie"].Expires = dtExpiry;
    }
    else
    {
           //If it does not - create a cookie, set its expiration and add it to the Response
           HttpCookie myCookie2 = new HttpCookie("MyCookie");
           myCookie2.Expires = DateTime.Now.AddDays(30);
           Response.Cookies.Add(myCookie2);
    }
    
    //Grab the cookie
    HttpCookie myCookie = Request.Cookies["MyCookie"];

    I may still be slightly confused at what is going on. But hopefully this is somewhat helpful.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, May 19, 2013 4:39 PM

All replies

  • User281315223 posted

    Could you post the code that you have when you are actually storing the cookie?

    It will need to match so if you are currently storing the cookie as "Bagperronen" and attempt to access it through "Bagperronen_Login" you are going to encounter your current NullReferenceException : 

    //Storing the Cookie
    HttpCookie cookie = new HttpCookie("Bagperronen");
    Response.Cookies.Add(cookie);
    
    //Accessing the cookie
    HttpCookie cookie = Request.Cookies["Bagperronen"];

    You may want to check out the Cookies Overview in ASP.NET for some additional information. 

    If you are encountering these issues within Internet Explorer, then there may be an issue with using underscores '_' within the names of cookies as mentioned in this blog post. Try replacing the underscore with a different delimiter such as a hyphen '-' or other character to see if that makes any difference.

    //Try using hyphens or some other character instead of underscores
    string siteTitle = config.SiteTitle.Replace(" ", "-");
    Sunday, May 19, 2013 4:14 PM
  • User-1798522060 posted

    Hi Rion

    thanks for your answer - to make it easier for you to read, I have made the set cookie just right before I want to get it - in real life the setCookie is in it's own method. I have also removed the underscore '_':

    public HttpCookie GetCookie(string cookieAddName)
        {
            WebConfigSettings config = new WebConfigSettings();
            string siteTitle = config.SiteTitle.Replace(" ", "_");
    
            if (siteTitle == String.Empty)
            {
                siteTitle = "Bagperronen";
            }
    
            siteTitle = siteTitle + "_" + cookieAddName;
    
    
    
            try
            {
                HttpCookie myCookie2 = new HttpCookie("MyCookie");
                //Response.Cookies.Remove(siteTitle);
                if (myCookie2 != null)
                {
                    DateTime dtExpiry = DateTime.Now.AddDays(30);
                    myCookie2.Expires = dtExpiry;
                }
                else
                {
                    Response.Cookies.Add(myCookie2);
                    DateTime dtExpiry = DateTime.Now.AddDays(30);
                    Response.Cookies[siteTitle].Expires = dtExpiry;
                }
    
                siteTitle = "MyCookie";
                HttpCookie myCookie = new HttpCookie(siteTitle);
                myCookie = Request.Cookies[siteTitle];
                //HttpCookie myCookie = Request.Cookies["Bagperronen_Login"];
                return myCookie;
            }
            catch
            {
                return null;
            }
    
            
            
        }


    As you can see - the names is the same - And I'm testing it in Firefox right now

    Sunday, May 19, 2013 4:24 PM
  • User281315223 posted

    If this is actually occuring within the same method (I could be confused) you aren't going to be able to access a cookie that was added to the Response object from the Request until after the Request has actually been made.  (In this case the cookie is never being added to the Response)

    For example : 

    //Create a cookie
    HttpCookie myCookie2 = new HttpCookie("MyCookie");
    
    //The cookie is guaranteed to exist as it was just created above
    if (myCookie2 != null)
    {
        //Add the appropriate properties
        DateTime dtExpiry = DateTime.Now.AddDays(30);
        myCookie2.Expires = dtExpiry;
    }
    else
    {
        //This will never be executed as the if-statement above will never be null
        Response.Cookies.Add(myCookie2);
        DateTime dtExpiry = DateTime.Now.AddDays(30);
        Response.Cookies["MyCookie"].Expires = dtExpiry;
    }
    
    //This will never return a value since the cookie is never added to the Response
    HttpCookie myCookie = Request.Cookies["MyCookie"];

    Instead of checking if the cookie is null, you may want to consider checking the Request to see if it is present as seen below : 

    //Check if the Cookie exists in the Response
    if (Response.Cookies["MyCookie"] != null)
    {
           //If it does - update the expiration
           DateTime dtExpiry = DateTime.Now.AddDays(30);
           Response.Cookies["MyCookie"].Expires = dtExpiry;
    }
    else
    {
           //If it does not - create a cookie, set its expiration and add it to the Response
           HttpCookie myCookie2 = new HttpCookie("MyCookie");
           myCookie2.Expires = DateTime.Now.AddDays(30);
           Response.Cookies.Add(myCookie2);
    }
    
    //Grab the cookie
    HttpCookie myCookie = Request.Cookies["MyCookie"];

    I may still be slightly confused at what is going on. But hopefully this is somewhat helpful.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, May 19, 2013 4:39 PM
  • User-1798522060 posted

    What I have and want: I'm using usercontrols about everything on my site. I've made a loginControl (placed on the frontpage). When logging in I want to look after a cookie - If it exist then update the expire if not exist create it.

    But when it exist I now in my MasterPage wants to check for the same thing. Checkin if the cookie exist and so on.

    I have made 4 methods (look below) to handle the above situation. But now (I have tried to use your suggestion) I again get the error: "Object reference not set to an instance of an object.". Now on the line if (Response.Cookies[siteTitle] != null)

    The 4 methods is:

    public HttpCookie GetCookie(string cookieAddName)
        {
            WebConfigSettings config = new WebConfigSettings();
            string siteTitle = config.SiteTitle.Replace(" ", "");
    
            if (siteTitle == String.Empty)
            {
                siteTitle = "Bagperronen";
            }
    
            try
            {
                HttpCookie myCookie = new HttpCookie(siteTitle);
                myCookie = Request.Cookies[siteTitle];
                //HttpCookie myCookie = Request.Cookies["Bagperronen_Login"];
                return myCookie;
            }
            catch
            {
                return null;
            }
        }
        public void SetCookieExpires(string cookieName, string UserName, string Password)
        {
            WebConfigSettings config = new WebConfigSettings();
            string siteTitle = config.SiteTitle.Replace(" ", "");
    
            if (siteTitle == String.Empty)
            {
                siteTitle = "Bagperronen";
            }
    
            //siteTitle = siteTitle + cookieName;
    
            HttpContext.Current.Response.Cookies[siteTitle].Expires = DateTime.Now.AddDays(30);
            HttpContext.Current.Response.Cookies[siteTitle].Values.Add("login", UserName);
            HttpContext.Current.Response.Cookies[siteTitle].Values.Add("pass", Password);
        }
        public HttpCookie SetCookie(string cookieAddName)
        {
            WebConfigSettings config = new WebConfigSettings();
            string siteTitle = config.SiteTitle.Replace(" ", "");
    
            if (siteTitle == String.Empty)
            {
                siteTitle = "Bagperronen";
            }
    
            //siteTitle = siteTitle + cookieAddName;
    
            if (Response.Cookies[siteTitle] != null)
            {
                DateTime dtExpiry = DateTime.Now.AddDays(30);
                Response.Cookies[siteTitle].Expires = dtExpiry;
            }
            else
            {
                //If it does not - create a cookie, set its expiration and add it to the Response
                HttpCookie myCookie2 = new HttpCookie(siteTitle);
                myCookie2.Expires = DateTime.Now.AddDays(30);
                Response.Cookies.Add(myCookie2);
            }
    
            //HttpCookie myCookie = new HttpCookie(siteTitle);
            //Response.Cookies.Add(myCookie);
            ////Response.Cookies.Remove(siteTitle);
            //if (myCookie != null)
            //{
            //    DateTime dtExpiry = DateTime.Now.AddDays(30);
            //    myCookie.Expires = dtExpiry;
            //}
            //else
            //{
            //    Response.Cookies.Add(myCookie);
            //    DateTime dtExpiry = DateTime.Now.AddDays(30);
            //    Response.Cookies[siteTitle].Expires = dtExpiry;
            //}
    
            HttpCookie myCookie = Request.Cookies[siteTitle];
    
            return myCookie;
    
        }
        public HttpCookie DelCookie(string cookieDelName)
        {
            WebConfigSettings config = new WebConfigSettings();
            string siteTitle = config.SiteTitle.Replace(" ", "");
    
            if (siteTitle == String.Empty)
            {
                siteTitle = "Bagperronen";
            }
    
            //siteTitle = siteTitle + cookieDelName;
    
            if (HttpContext.Current.Response.Cookies[siteTitle] != null)
            {
                HttpContext.Current.Response.Cookies[siteTitle].Value = null;
                HttpContext.Current.Response.Cookies[siteTitle].Expires = DateTime.Now.AddMonths(-1);
            }
    
            HttpCookie myCookie = Request.Cookies[siteTitle];
    
            return myCookie;
    
        }



    Sunday, May 19, 2013 5:02 PM