Asp.net

如何在 ASP.NET 4.0 中進行 301 重定向?

  • April 29, 2019

我正在嘗試為網站實現 URL 重定向,而不是逐頁進行。我想在 global.asax 文件中執行此操作。下面是我定義的程式碼。

我想將http://website.net作為我的主要網址,並且如果有人輸入 http://www.website.net ,我希望有一個永久的網址重定向

不幸的是,它不適用於實時網站。誰能指出程式碼中的問題。該程式碼不會產生任何錯誤。

void Application_Start(object sender, EventArgs e) 
{
   // Code that runs on application startup

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

}

主要問題:您正在執行上述Application_Start操作 - 僅執行一次。您應該聯繫每個請求。嘗試這個:

void Application_BeginRequest(object sender, EventArgs e) 
{
   // Code that runs on every request

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

}

更好的方法是使用 URL 重寫,它可以從內部配置Web.Config

Microsoft 重寫模組 - 在 url 上強制 www 或從 url 中刪除 www

引用自:https://stackoverflow.com/questions/10673303