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

在 global.asax 中實作 URL 重寫

     編輯:關於ASP.NET

許多網站都會使用 URL 重寫功能,讓網址更簡潔、利於 SEO 且隱藏查詢字串參數。網路上雖有多種實作方式,但大多較為複雜難懂。本文介紹一個簡單易懂的方法:只需在 global.asax.cs 中加入 Application_BeginRequest 事件處理函式,即可輕鬆實現 URL 重寫。

核心程式碼範例

protected void Application_BeginRequest(Object sender, EventArgs e)
{
    string oldUrl = HttpContext.Current.Request.RawUrl;

    // 新聞頁面重寫規則:/News12.html → NewsDetails.aspx?NID=12
    string pattern = @"^(.+)News(\d+).html(\?.*)*$";
    string replace = "$1NewsDetails.aspx?NID=$2";

    // 文化頁面重寫規則:/Culture12.html → CultureDetails.aspx?CID=12
    string patternCul = @"^(.+)Culture(\d+).html(\?.*)*$";
    string replaceCul = "$1CultureDetails.aspx?CID=$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);
    }
    if (Regex.IsMatch(oldUrl, patternCul, RegexOptions.IgnoreCase | RegexOptions.Compiled))
    {
        string newUrl = Regex.Replace(oldUrl, patternCul, replaceCul, RegexOptions.Compiled | RegexOptions.IgnoreCase);
        this.Context.RewritePath(newUrl);
    }
}

運作原理解析

  • 使用正則表達式比對傳入的原始 URL (Request.RawUrl)
  • 符合模式時,利用 Regex.Replace 將其轉換為實際的 .aspx 頁面並帶入查詢參數
  • 呼叫 Context.RewritePath 進行伺服器端重導向,瀏覽器網址列保持原樣

優點與應用

此方法可同時實現多組重寫規則,只需依需求增減 pattern 與 replace 變數。重寫後將 GET 參數隱藏於友善網址中,不僅提升安全性,也讓使用者誤以為網站採用靜態頁面。只要伺服器支援,配合強大的正則表達式,幾乎能實現任意形式的 URL 重寫。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved