2011-01-21 94 views
2

可以請你告訴我,如何使301永久重定向在asp.net?如何使301永久重定向在asp.net

我在Global.asax文件編寫的代碼,但我的Web客戶端說,這是行不通的,

我已經寫在Global.asax文件follwing代碼:

protected void Application_BeginRequest(object sender, EventArgs e) 
    { 
     if (HttpContext.Current.Request.Url.ToString().ToLower().Contains(
"http://lsatfreedom.com")) 
     { 
      HttpContext.Current.Response.Status = 
       "301 Moved Permanently"; 
      HttpContext.Current.Response.AddHeader("Location", 
       Request.Url.ToString().ToLower().Replace(
        "http://lsatfreedom.com", 
        "http://www.lsatfreedom.com")); 
     } 

    } 

是它有用嗎? 請幫忙。

謝謝

+0

如果你想整個網站重定向爲什麼不IIS重定向? – Shoban 2011-01-21 04:40:34

+0

請告訴我如何檢查它是否工作? – tina 2011-01-21 04:51:41

+0

如果是IIS7,請檢查以下鏈接:http://www.davelawlor.com/iis-7-setup-301-redirect – Shoban 2011-01-21 04:52:39

回答

2

首先嚐試查看此重定向是否在頁面加載中工作。 如果是,則使用Begin_Request進行嘗試。

希望這給你一些線索:

private void Page_Load(object sender, System.EventArgs e) 
{ 
Response.Status = "301 Moved Permanently"; 
Response.AddHeader("Location","http://www.new-url.com"); 
} 
1

我相信你缺少一個CompleteRequest()

所以,你的代碼應該是這樣的:

if (HttpContext.Current.Request.Url.ToString().ToLower().Contains(
     "http://lsatfreedom.com")) 
    { 
     HttpContext.Current.Response.Status = 
      "301 Moved Permanently"; 
     HttpContext.Current.Response.AddHeader("Location", 
      Request.Url.ToString().ToLower().Replace(
       "http://lsatfreedom.com", 
       "http://www.lsatfreedom.com")); 
     CompleteRequest(); 
    } 

如果不加完成請求,然後ASP.Net將嘗試自己處理它,在這種情況下,頭可能存在,但實際上可能會在開始響應和結束它。這將使它不會得到實際的重定向。

2

我認爲你缺少Response.Clear()Response.End(),請與此嘗試。

例如:

protected void Application_BeginRequest(object sender, EventArgs e) 
    { 
     if (HttpContext.Current.Request.Url.ToString().ToLower().Contains(
"http://lsatfreedom.com")) 
     { 
      string sNewPage = Request.Url.ToString().ToLower().Replace(
        "http://lsatfreedom.com", 
        "http://www.lsatfreedom.com"); 

      Response.Clear(); 
      Response.Status = "301 Moved Permanently"; 
      Response.AddHeader("Location", sNewPage); 
      Response.End(); 
     } 
    }