2011-05-11 59 views
2

我在這裏下面的代碼http://www.4guysfromrolla.com/articles/072810-1.aspxASP.NET網站重定向幫助

重定向到http://somesite.comhttp://www.somesite.com

protected void Application_BeginRequest(object sender, EventArgs e) 
{ 
    if (Request.Url.Authority.StartsWith("www")) 
     return; 

    var url = string.Format("{0}://www.{1}{2}", 
       Request.Url.Scheme, 
       Request.Url.Authority, 
       Request.Url.PathAndQuery); 

    Response.RedirectPermanent(url, true); 
} 

如何使用這個代碼來處理的情況下http://abc.somesite.com應該重定向到www.somesite .com

回答

0
  1. 如果你不知道該值將時間提前了什麼,你可以使用子用的indexOf的URL路徑解析出你想要的值,並替換它。

  2. 如果您確實知道提前發生的情況,您可以隨時執行Request.Url.PathAndQuery.Replace(「abc」,「www」);

你也可以做一個dns檢查@aceinthehole建議你解析了你需要的東西,以確保你沒有犯任何錯誤。

假設你有一個像http://abc.site.com這樣的字符串,你想把abc變成www然後你可以做類似的事情。

string pieceToReplace = Request.Url.PathAndQuery.substring(0, Request.Url.PathAndQuery.IndexOf(".") + 1); 

//here I use the scheme and entire url to make sure we don't accidentally replace an "abc" that belongs later in the url like in a word "GHEabc.com" or something. 
string newUrl = Request.Url.ToString().Replace(Request.Url.Scheme + "://" + pieceToReplace, Request.Url.Scheme + "://www"); 

Response.Redirect(newUrl); 

p.s.我不記得Request.Url.Scheme中是否已經包含「://」,因此您需要進行相應的編輯。

+0

我沒有訪問DNS的權限。我也沒有提到價值。我只需要http://somevalue.somesite.com重定向到www.somsite.com。你能提供一些代碼嗎? – 2011-05-11 19:05:09

1

我建議最好的辦法來處理這將是在DNS記錄,如果你有它的控制。

0

我不認爲你可以做到這一點,而無需訪問DNS。這聽起來像你需要一個通配符DNS條目:

http://en.wikipedia.org/wiki/Wildcard_DNS_record

隨着無主機頭配置IIS(僅基於IP)。然後你可以使用類似於上面的代碼來做你想做的事情。

if (!Request.Url.Host.StartsWith ("www") && !Request.Url.IsLoopback) 
    Response.Redirect('www.somesite.com'); 

也許收緊一些,以防止wwww.somesite.com通過。任何以www開頭的內容(包括wwwmonkeys.somesite.com)都將通過上述檢查。這只是一個例子。

asp.net mvc: How to redirect a non www to www and vice versa