Cookies Mod for ShoppingCart.cs

Jan 22, 2015 at 8:39 PM
In case this is useful for anyone, I modified the GetCartId method to use cookies instead of session.

@jongalloway commented somewhere in this discussion area about how to do this but there were a few subtle changes here and there that needed to be made (namely using Response(write the cookie) and Request(read the cookie) at the appropriate time & reading/writing to .Value property of the cookie).

This seems to work for me. In checking the cookies/values in my browser (Firefox > tools > options > privacy > Show cookies) the cookie sets fine for anonymous and an auth user.

If anybody sees any glaring coding no-nos or if this code is outdated please feel free to post.

        public string GetCartId(HttpContextBase context)
            // Checks to see if cookie exists
            if (context.Request.Cookies[CartSessionKey] == null)
                // If no cookie exists check for logged in user name and assign it to cookie value
                if (!string.IsNullOrWhiteSpace(context.User.Identity.Name))
                    //assign cookie value of the username
                    context.Response.Cookies[CartSessionKey].Value = context.User.Identity.Name;
                // If the user is anonymous assign a random guid to cookie value
                    Guid tempCartId = Guid.NewGuid();
                    //assign cookie the value of the Guid
                    context.Response.Cookies[CartSessionKey].Value = tempCartId.ToString();
            //return whatever value was set in the cookie
            return context.Request.Cookies[CartSessionKey].Value.ToString();