2014-02-12 51 views
0

我正在重新設計一個網站,新網站帶有URL路由功能,並且需要更改一些舊網址。但我想正確地將舊網址的用戶重定向到網站的新網址。比較URL和if語句以正確重定向到新URL

舊的URL http://www.abc.com/about 新URL http://www.abc.com/about-us

所以想用下面的代碼做它global.asx文件。

if (HttpContext.Current.Request.Url.ToString().ToLower().Contains("http://www.abc.com/about")) 
{ 
    HttpContext.Current.Response.Status = "301 Moved Permanently"; 
    HttpContext.Current.Response.Redirect("http://www.abc.com/about-us"); 
} 

但是,這將觸發代碼執行以下

http://www.abc.com/about 
http://www.abc.com/about-us 
http://www.abc.com/about-us/history 
http://www.abc.com/about-us/vision 

什麼是比較URL的更好的辦法,我應該用一個簡單的老學校if (A == B)或者是他們做的更好的辦法中提到的所有網址它

if (HttpContext.Current.Request.Url.ToString().ToLower().Equals("http://www.abc.com/about") 
{ 
    HttpContext.Current.Response.Status = "301 Moved Permanently"; 
    HttpContext.Current.Response.Redirect("http://www.abc.com/about-us"); 
} 

或使用本

if (HttpContext.Current.Request.Url.ToString().ToLower()=="http://www.abc.com/about") 
{ 
    HttpContext.Current.Response.Status = "301 Moved Permanently"; 
    HttpContext.Current.Response.Redirect("http://www.abc.com/about-us"); 
} 

正則表達式也可以使用,但我不善於和將它,除非我不是絕對確定。

有什麼建議,在這種情況下

UPDATE:決定做這樣

if (HttpContext.Current.Request.Url.ToString().ToLower().Equals("http://www.abc.com/about") || (HttpContext.Current.Request.Url.ToString().ToLower().Equals("http://www.abc.com/about/") 
{ 
    HttpContext.Current.Response.Status = "301 Moved Permanently"; 
    HttpContext.Current.Response.Redirect("http://www.abc.com/about-us"); 
} 
+0

而不是使用這我建議你在web.config中編寫重寫規則。 –

回答

0

嘗試檢查響應狀態代碼以及之前重定向: -

if (HttpContext.Current.Request.Url.ToString().ToLower()=="http://www.abc.com/about" 
&& HttpContext.Current.Response.StatusCode!=301) 
{ 
    HttpContext.Current.Response.Status = "301 Moved Permanently"; 
    HttpContext.Current.Response.StatusCode = 301; 
    HttpContext.Current.Response.Redirect("http://www.abc.com/about-us"); 
} 
+0

如何使用'ToLower()。Equals(「http://www.abc.com/about」)' – Learning

0

您可以執行以下操作:

if(HttpContext.Current.Request.Url.ToString().ToLower().EndsWith("abc.com/about")) 
{ 
    HttpContext.Current.Response.Status = "301 Moved Permanently"; 
    HttpContext.Current.Response.Redirect("http://www.abc.com/about-us"); 
} 
0

由於最終用戶可以輸入 「abc.com/about」 或 「www.abc.com/about」

試試這個:

if (Request.Url.ToString().ToLower().Contains("abc.com/about")) 
     Response.Redirect("http://www.abc.com/about-us"); 

感謝

+0

我想你的意思是'abc.com/about'或'abc.com/about /'我已經做到這一點,並決定按照我的問題更新 – Learning