2012-03-28 60 views
0

我想在asp.net頁面中檢測傳入url並在該url的基礎上做出一些決定但是我在這裏面臨的一些問題是我的c#代碼檢測URL和條件基於傳入的url調用url

<script runat="server"> 

    protected void Page_Load(object sender, EventArgs e) 
    { 
     if (!IsPostBack) 
     { 
     String url = Request.ServerVariables["HTTP_REFERER"]; 
     if (url != "http://172.17.0.221:84/CP.aspx") 
     { 
      Response.Redirect("http://a.sml.com.pk"); 
     } 
     else 
     { 
      Response.Redirect("http://172.17.0.221:85/MilkSale.aspx"); 
     } 

     }   
    }  

</script> 

但是當我調用的頁面從http://172.17.0.221:84/CP.aspx則給出了這樣的錯誤:

This webpage has a redirect loop.

The webpage at http://172.17.0.221:85/MilkSale.aspx has resulted in too many redirects. Clearing your cookies for this site or allowing third-party cookies may fix the problem. If not, it is possibly a server configuration issue and not a problem with your computer.

任何一個可以告訴我可以在這代碼中的錯誤?

+0

它看起來像重定向多次到同一頁面。記錄正在處理的頁面的URL以確保。嘗試調用'Response.End'來結束處理。 – 2012-03-28 09:57:35

+0

該腳本是否也在MilkSale.aspx頁面上?如果是這樣,它會每隔*時間發射一次。更改你的其他地址,如果url!=「http://172.17.0.221:85/MilkSale.aspx」{}來檢查這個。 – dash 2012-03-28 10:01:50

+0

看起來像你導致永無止境的頁面重定向..可能它總是去**其他**部分。嘗試使用**否則如果**而不是**其他** – 2012-03-28 10:03:49

回答

2

如果您的腳本語句也在MilkSale.aspx頁面上,那麼每次頁面被擊中時它都會觸發;實際上,它將永遠重定向到自己(或者,在這種情況下,直到asp.net檢測到它一遍又一遍地請求同一頁面)。

首先:

protected void Page_Load(object sender, EventArgs e) 
{ 
    if (!IsPostBack) 
    { 
    String url = Request.ServerVariables["HTTP_REFERER"]; 
    if(!String.IsNullOrEmpty(url)) 
    { 
     if (!url.ToUpper().Contains("CP.ASPX")) 
     { 
      Response.Redirect("http://a.sml.com.pk"); 
     } 
     else if (!url.ToUpper().Contains("MILKSALE.ASPX") && !url.ToUpper().Contains("CP.ASPX")) 
     { 
      Response.Redirect("http://172.17.0.221:85/MilkSale.aspx"); 
     } 
    } 

    }   
} 

那麼這將解決第一個問題。但是,您必須考慮代碼中的其他問題;

  1. 您正在做不區分大小寫的字符串匹配。
  2. 您有IP地址在您的網址

1)是很容易使用硬編碼;例如,您可以使用String.Compare(url, referrer, StringComparison.InvariantCultureIgnoreCase)。在我的代碼中,我使用了.ToUpper(),但這仍然充滿了問題(但是爲了一個簡潔的例子)

2)更困難;你應該真的把你的重定向機制與根URL關聯起來,否則你每次更改網站時都必須更改你的代碼。請使用屬性HttpContext.Current.Request.Url.PathAndQuery或者最好查看URL rewriting

+0

可能這將工作! – 2012-03-28 10:04:46

+0

沒有同一個錯誤顯示 – 2012-03-28 10:09:23

+0

url是否爲空?請參閱編輯。另外,請嘗試寫出URL;你的問題是,別人總是射擊:-) – dash 2012-03-28 10:12:51