首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

虛擬主機環境下 ASP.NET 實作 URL Rewrite(Global.asax + Regex)

     編輯:關於ASP.NET

常見誤區

  • HttpHandler 無法實作 URL Rewrite。
  • Server.Transfer 是伺服器端轉向,非 URL Rewrite(瀏覽器網址不變)。

虛擬主機可行方案:Global.asax Application_BeginRequest

虛擬主機無法修改 IIS 設定、安裝 ISAPI Rewrite 模組,但可在 Application_BeginRequest 事件攔截請求,使用正則重寫路徑並呼叫 Context.RewritePath。

protected void Application_BeginRequest(Object sender, EventArgs e)
{
    string oldUrl = HttpContext.Current.Request.RawUrl;
    string pattern = @"^(.+)default/(\d+)\.aspx(\?.*)*$";
    string replace = "$1default.aspx?id=$2";

    if (Regex.IsMatch(oldUrl, pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled))
    {
        string newUrl = Regex.Replace(oldUrl, pattern, replace, RegexOptions.Compiled | RegexOptions.IgnoreCase);
        this.Context.RewritePath(newUrl);
    }
}

運作結果

瀏覽 /default/123.aspx → 內部重寫為 /default.aspx?id=123,瀏覽器網址列保持原狀,使用者無感知。

擴充性

  • 自行定義正則規則,支援任意 URL 模式對應。
  • 自有伺服器可在 IIS 映射副檔名(如 *.myweb),虛擬主機通常僅支援 .aspx 等已映射副檔名。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved