2014-10-18 94 views
0

我使用下面的頁面加載代碼,但它給了我下面的錯誤不設置到對象的實例如何捕捉父頁面的iframe中頁面的URL(UTM參數),

「對象引用「。

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; 

     } 
    } 

回答

3

是的,你是做正確的,但你需要把null檢查首先使用它們之前。以下是一些可以改進的代碼。使用此if(Request.UrlReferrer!=null && !string.IsNullOrEmpty(Request.UrlReferrer.OriginalString))而不是if (Request.UrlReferrer.OriginalString.ToString() != null)

使用此Request.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,其具有與iFrame = srctest1.aspx。我使用了http://localhost:52785/test2.aspx?k=1&m=2網址,因此父頁的查詢串爲k=1, m=2。看下面的截圖,我得到了什麼。

enter image description here

+0

尊敬的@Arindam,感謝您的解決方案,但它的工作不正常,它給我錯誤 「對象引用未設置爲對象的實例。」 – Abhi 2014-10-18 09:08:27

+0

你能告訴我它在哪一行顯示錯誤嗎?你可以調試,然後你可以檢查。 – 2014-10-18 09:12:00

+1

嗨Arindam,這是一些其他的愚蠢的錯誤,否則你的代碼是非常有用的。謝謝你很多。 – Abhi 2014-10-18 09:54:44

0

你可以試試下面的JavaScript,但只有在iframe和周圍都來自同一個域(同源策略)的網站。

var uri = document.getElementById("IdOfIframe").contentWindow.location.href; 
+0

嘿丹尼爾,我的問題是網站和iframe都在不同的服務器上。 :( – Abhi 2014-10-18 08:35:28