6
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        if (Request.Browser.Cookies)
        {
            if (Request.QueryString["check"] == null)
            {
                HttpCookie cookie = new HttpCookie("testcookie");
                Response.Cookies.Add(cookie);
                Response.Redirect("Default.aspx?check=1");
            }
            else
            {
                HttpCookie cookie = Request.Cookies["testcookie"];
                if(cookie==null)
                {
                    Label1.Text = "enable cookies";
                }
            }
        }
        else
        {
            Label1.Text = "cookies not supported:";
        }
    }
}

protected void Button1_Click(object sender, EventArgs e)
{
    HttpCookie cookie = new HttpCookie("userinfo");
    cookie["name"] = TextBox1.Text;
    cookie["email"] = TextBox2.Text;
    //cookie.Expires = DateTime.Now.AddDays(30);
    Response.Cookies.Add(cookie);
    Response.Redirect("Default2.aspx");

}

It's not working correctly.

Mrunal
  • 13,982
  • 6
  • 52
  • 96
Kasirajan
  • 99
  • 2
  • 3
  • 9
  • possible duplicate http://stackoverflow.com/questions/210321/best-way-to-determine-if-cookies-are-enabled-in-asp-net – mas_oz2k1 Jan 09 '15 at 00:01

1 Answers1

11

See the following link.

http://forums.asp.net/t/1044823.aspx?How+to+check+cookies+enabled+in+a+web+browser+

The only way to check is set a cookie then redirect it and again check if you are able to access it or not. So try below method mentioned in above link.

protected void Page_Load(object sender, EventArgs e)
{
    if (this.IsCookieDisabled())
      errorMsgLabel.Text = Resources.Resource.BrowserDontSupportCookies;

}


private bool IsCookieDisabled()
{
 string currentUrl = Request.RawUrl;

 if (Request.QueryString["cookieCheck"] == null)
 {
     try
     {
            HttpCookie c = new HttpCookie("SupportCookies", "true");
            Response.Cookies.Add(c);

            if (currentUrl.IndexOf("?") > 0)
                currentUrl = currentUrl + "&cookieCheck=true";
            else
                currentUrl = currentUrl + "?cookieCheck=true";

            Response.Redirect(currentUrl);
       }
       catch(Exception ex)
       {
          return false;
       }
 }

 if (!Request.Browser.Cookies || Request.Cookies["SupportCookies"] == null)
      return true;

return false;
}
Jalpesh Vadgama
  • 13,653
  • 19
  • 72
  • 94
  • This won't work if the user bookmarks the full URL, including the cookieCheck parameter. – Ash Oct 31 '16 at 12:09
  • To distinguish what @Ash points out, you could set the Value of `cookieCheck` as date `yyyyMMddHHmmss` . When receiving the call, you parse the the date and check if the difference to to `DateTime.Now` is not more than a couble of seconds. Alternative: you could set a `Guid` and store it in the server-cache for short amount of time... (there are solutions :-)) – spaark Nov 16 '18 at 05:35