Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Hey guys i get this error when i try to assign CartID to a string. Would really appreciate any help. Thanks

private static string CartID
{
    get
    {
        HttpContext cont = HttpContext.Current;
        string id = cont.Request.Cookies["ShopCartID"].Value;

        if (cont.Request.Cookies["ShopCartID"] != null)
        {
            return id;
        }
        else
        {
            id = Guid.NewGuid().ToString();
            HttpCookie cookie = new HttpCookie("ShopCartID", id);
            int days = 7;
            DateTime currentDate = DateTime.Now;
            TimeSpan timeSpan = new TimeSpan(days, 0, 0, 0);
            DateTime expiration = currentDate.Add(timeSpan);
            cookie.Expires = expiration;
            cont.Response.Cookies.Add(cookie);
            return id.ToString();
        }
    }
}
share|improve this question

2 Answers

up vote 0 down vote accepted

There is no CartID in your question (other than the class itself) so I will assume you mean ShopCartID.

cont.Request.Cookies["ShopCartID"] could return null if a cookie with that name doesn't exist. You can't call members (in this case, Value) on a null reference. You have to first check if the cookie is null:

HttpCookie cookie = cont.Request.Cookies["ShopCartID"];
string id = cookie != null ? cookie.Value : null;
share|improve this answer

Try putting your null check before accessing the cookie value. Currently, your code calls cont.Request.Cookies["ShopCartID"].Value, which will fail if the cookie isn't there.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.