-2

I am getting nullpointerexception at if condition . How to resolve this error. My code and error decription is below.

error :An exception of type 'System.NullReferenceException' occurred in System.Web.dll but was not handled in user code

error occurs on this line: if (Request.Cookies[name].Value != null)

  public void SetCookie(string name, string value, int expiration)
    {
        HttpCookie cookie;
        cookie = new HttpCookie(name);
        if (Request.Cookies[name].Value != null)
        {
            DeleteCookie(name);
        }
        else
        {
            cookie.Value = value;
            cookie.Expires = DateTime.Now.AddDays(expiration);
            Response.Cookies.Add(cookie);
        }

    }

1 Answers1

0

Change your method to the following:

 public void SetCookie(string name, string value, int expiration)
{
    if(Request.Browser.Cookies)
    {
        if (Request.Cookies[name] != null)
        {
            DeleteCookie(name);
        }

        HttpCookie cookie;
        cookie = new HttpCookie(name);
        cookie.Value = value;
        cookie.Expires = DateTime.Now.AddDays(expiration);
        Response.Cookies.Add(cookie);
    }
}
meda
  • 45,103
  • 14
  • 92
  • 122