1 Replies - 2735 Views - Last Post: 22 November 2013 - 02:15 PM Rate Topic: -----

#1 djasy   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 02-February 12

Object reference not set to an instance of an object(CartID)

Posted 21 November 2013 - 07:51 PM

hi, i'm developping a shopping cart with asp.net/C#
i am trying to return the shopping cart id using cookies. but i have that an exeption as written in the subject.
here is my method:(sorry my comments are in french)
/*retourne l'ID du shoppingCart du visiteur ou utilisateur sur le site*/
    private static string ShoppingCartId
            //on obtient le HttpContext actuel
            HttpContext context = HttpContext.Current;
            //on essaie d'extraire l'id stockés dans le cookie de l'utilisateur actuel
            string cartId = context.Request.Cookies["LUP_CartID"].Value;
            //si l'id du Cart n'est pas dans le cookie
                //on vérifie si l'id du cart existe en tant que cookie
                if (context.Request.Cookies["LUP_CartID"] != null)
                    //on retourne l'id
                    //cartId = context.Request.Cookies["LUP_CartID"].Value;
                    return cartId;
                    //si l'id du cart n'existe pas dans le cookie, on génère un new id
                    //en générant un GUID(Globally Unique IDentifier
                    cartId = Guid.NewGuid().ToString();
                    //on créer un cookie et on lui attribue une valeur
                    HttpCookie cookie = new HttpCookie("LUP_CartID", cartId);
                    //on définie le nombre de jours du cookie
                    int nbreDejours = LibConfig.CartPersistDays;
                    DateTime dateActuelle = DateTime.Now;
                    //pour obtenir une intervalle de temps: structure
                    TimeSpan intevalTemps = new TimeSpan(nbreDejours, 0, 0,0);
                    //on définit la date d'expiration
                    DateTime dateExpiration = dateActuelle.Add(intevalTemps);
                    cookie.Expires = dateExpiration;
                    //on définit le cookie dans le navigateur du client
                    //on retourne l'id du cart
                    return cartId.ToString();

sorry i forgot to write where the error comes from:
the error comes from the 9th line
string cartId = context.Request.Cookies["LUP_CartID"].Value;

Is This A Good Question/Topic? 0
  • +

Replies To: Object reference not set to an instance of an object(CartID)

#2 demausdauth   User is offline

  • D.I.C Addict
  • member icon

Reputation: 190
  • View blog
  • Posts: 692
  • Joined: 03-February 10

Re: Object reference not set to an instance of an object(CartID)

Posted 22 November 2013 - 02:15 PM

You should put your cartId assignment after you check for a valid value in the cookie.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1