0

我在页面加载时使用下面的代码,但它给了我以下错误

“你调用的对象是空的。”

protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {

            if (("" + Request.QueryString["utm_source"] == "") && ("" + Request.QueryString["utm_medium"] == "") || ("" + Request.QueryString["utm_source"] == null) && ("" + Request.QueryString["utm_medium"] == null))
            {
                lblSource.Text = "Direct/Referral";
            }
            else
            {
                try
                {
                    if (Request.UrlReferrer.OriginalString.ToString() != null)
                    {
                        string abc = Request.UrlReferrer.OriginalString.ToString();

                        string[] source = abc.Split('?');
                        string a1 = source[1];

                        a1 = a1.Substring(11);

                        string[] spl = a1.Split('&');

                        utm_source = spl[0];
                        string a2 = spl[1];

                        utm_medium = a2.Substring(11);
                    }
                }
                catch (Exception ex)
                {
                    //Response.Write(ex);
                    lblSource.Text = "Direct/Referral";
                }
            }
            //Response.Write(utm_source + "   " + utm_medium);

                lblSource.Text = utm_source + " " + utm_medium;

        }
    }
4

2 回答 2

3

是的,你做对了,但null在使用它们之前你需要先检查。以下是一些可以改进的代码。

使用它if(Request.UrlReferrer!=null && !string.IsNullOrEmpty(Request.UrlReferrer.OriginalString))而不是if (Request.UrlReferrer.OriginalString.ToString() != null).

使用 thisRequest.QueryString["utm_source"] != null而不是Request.QueryString["utm_source"] == "",因为它会尝试将其转换为字符串以进行比较,并且该值为null,它将错误为"Object reference not set to an instance of an object."

要获得准确的查询字符串,您可以从 iFrame 中这样做,而不是字符串操作。

protected void Page_Load(object sender, EventArgs e)
{
    Uri parenturl = new Uri(Request.UrlReferrer.OriginalString);
    string qyr = parenturl.Query;
    NameValueCollection col = HttpUtility.ParseQueryString(qyr);
    String kvalue = col["k"];
    String mvalue = col["m"];
}

假设: 上面的代码属于,我还有test1.aspx一页test2.aspx有= 。我使用了url,所以父页面的查询字符串为. 看下面的截图,我得到了什么。iFramesrctest1.aspxhttp://localhost:52785/test2.aspx?k=1&m=2k=1, m=2

在此处输入图像描述

于 2014-10-18T08:32:04.670 回答
0

您可以尝试以下 JavaScript,但前提是 iframe 和周围的站点来自同一个域(同源策略)。

var uri = document.getElementById("IdOfIframe").contentWindow.location.href;
于 2014-10-18T08:16:53.040 回答