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

前端之家收集整理的这篇文章主要介绍了c# – 如何在asp.net中检查cookie是启用还是禁用?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. protected void Page_Load(object sender,EventArgs e)
  2. {
  3. if (!IsPostBack)
  4. {
  5. if (Request.Browser.Cookies)
  6. {
  7. if (Request.QueryString["check"] == null)
  8. {
  9. HttpCookie cookie = new HttpCookie("testcookie");
  10. Response.Cookies.Add(cookie);
  11. Response.Redirect("Default.aspx?check=1");
  12. }
  13. else
  14. {
  15. HttpCookie cookie = Request.Cookies["testcookie"];
  16. if(cookie==null)
  17. {
  18. Label1.Text = "enable cookies";
  19. }
  20. }
  21. }
  22. else
  23. {
  24. Label1.Text = "cookies not supported:";
  25. }
  26. }
  27. }
  28.  
  29. protected void Button1_Click(object sender,EventArgs e)
  30. {
  31. HttpCookie cookie = new HttpCookie("userinfo");
  32. cookie["name"] = TextBox1.Text;
  33. cookie["email"] = TextBox2.Text;
  34. //cookie.Expires = DateTime.Now.AddDays(30);
  35. Response.Cookies.Add(cookie);
  36. Response.Redirect("Default2.aspx");
  37.  
  38. }

它无法正常工作.

@H_403_7@解决方法
请参阅以下链接.

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

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

  1. protected void Page_Load(object sender,EventArgs e)
  2. {
  3. if (this.IsCookieDisabled())
  4. errorMsgLabel.Text = Resources.Resource.BrowserDontSupportCookies;
  5.  
  6. }
  7.  
  8.  
  9. private bool IsCookieDisabled()
  10. {
  11. string currentUrl = Request.RawUrl;
  12.  
  13. if (Request.QueryString["cookieCheck"] == null)
  14. {
  15. try
  16. {
  17. HttpCookie c = new HttpCookie("SupportCookies","true");
  18. Response.Cookies.Add(c);
  19.  
  20. if (currentUrl.IndexOf("?") > 0)
  21. currentUrl = currentUrl + "&cookieCheck=true";
  22. else
  23. currentUrl = currentUrl + "?cookieCheck=true";
  24.  
  25. Response.Redirect(currentUrl);
  26. }
  27. catch(Exception ex)
  28. {
  29. return false;
  30. }
  31. }
  32.  
  33. if (!Request.Browser.Cookies || Request.Cookies["SupportCookies"] == null)
  34. return true;
  35.  
  36. return false;
  37. }

猜你在找的C#相关文章