如果QueryString变量存在,则在ASP.Net中的会话启动时设置Cookie

时间:2017-02-02 01:49:15

标签: asp.net

我希望更准确地跟踪将流量发送到我的asp.net网站的营销计划。目前,我已经编写了单独的页面来查找引用查询字符串参数" gclid"。

示例:http://example.com/landingpage.aspx?gclid=[vlue]

我希望有一种方法可以让我的网站中的任何目标网页实现此流程全局,并且只有在目标网页的查询字符串中找到时,才会将Cookie设置为等于gclid的值。

这是用Session_OnStart可靠地完成的吗?

2 个答案:

答案 0 :(得分:1)

是的,Session_Start是一种可行的方法。

此时HttpContext.Current有效,因此您可以使用HttpContext.Current.Request.QueryString到达查询字符串,即

var gclid = HttpContext.Current.Request.QueryString["gclid"];

答案 1 :(得分:1)

Session_Start文件中的Global.asax事件是您可以使用的另一种选择。请参阅@ sh1rts的回答。

Session_Start事件(当然)仅在启动新会话时触发。假设情况:

  1. 用户点击其他网站上的链接并到达您的网站
  2. Session_Start运行并将gclid值存储到新会话
  3. 用户返回其他网站
  4. 不久之后,用户点击了另一个链接,再次访问了您的网站
  5. 用户已在您的网站上开设了会话,因此不会再次触发Session_Start
  6. 如果gclid第二次不同,则不会使用该值更新会话。这在实践中可能不是问题,因此Session_Start可能是一个解决方案。如果此可能成为问题,那么您可以在Global.asax中使用针对每个请求运行的其他事件。例如Application_PostAcquireRequestState

    void Application_PostAcquireRequestState(object sender, EventArgs e)
    {
        var httpApp = sender as HttpApplication;
        if(httpApp != null && httpApp.Context != null && httpApp.Context.Session != null)
        {
            if(!string.IsNullOrEmpty(httpApp.Context.Request.QueryString["gclid"]))
                httpApp.Context.Session["gclid"] = httpApp.Context.Request.QueryString["gclid"];
        }
    }