c# – 如何在asp.net中检查cookie是启用还是禁用?

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");

}

它无法正常工作.

解决方法

请参阅以下链接.

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

唯一的检查方法是设置一个cookie然后重定向它,然后再次检查你是否能够访问它.所以尝试以上链接中提到的方法.

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;
}

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...