无法正确读取cookie

时间:2018-05-21 10:45:25

标签: asp.net

我有一个cookie栏,可以安装一个名为“CookiePolicy”的cookie来存储用户首选项(当然,值为1 = OK状态)。

我需要使用此值来激活/停用我的网站上的Google Analytics。 我觉得这很容易......但这真是一团糟! :(

我的代码

<script runat="server">
protected void Page_Load(object sender, EventArgs e)   {
   HttpCookie cookie = Request.Cookies.Get("CookiePolicy");

   if( cookie.Value != "1" ){ 
      Response.Write("<script>");
      Response.Write("function (i, s, o, g, r, a, m) {");
      Response.Write("i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {");
      Response.Write("(i[r].q = i[r].q || []).push(arguments)");
      Response.Write("}, i[r].l = 1 * new Date(); a = s.createElement(o),");
      Response.Write("m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)");
      Response.Write("})(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');");
      Response.Write("ga('create', 'UA-xxxxx-x', 'auto');");
      Response.Write("ga('send', 'pageview');");

  }
} 

</script>

我收到各种错误。怎么了?

最糟糕的是...... System.NullReferenceException:对象引用未设置为对象的实例。(由if子句发出)

1 个答案:

答案 0 :(得分:1)

请试试这个:

HttpCookie cookie = Request.Cookies["CookiePolicy"];

用于检查null

if (cookie == null) {
   Response.Write("Cookie not found.");
}

参考:http://www.informit.com/articles/article.aspx?p=25045&seqNum=4