虛擬主機無權修改 IIS 設定、安裝 ISAPI Rewrite 模組。但 ASP.NET 管線允許在 Global.asax 的 Application_BeginRequest 事件中攔截請求並重寫路徑,僅限 .aspx 等已對應 ASP.NET 的副檔名。
Global.asax.cs (或 Global.asax 配合 <script runat="server">)。Application_BeginRequest 方法,加入重寫邏輯:protected void Application_BeginRequest(Object sender, EventArgs e)
{
string oldUrl = HttpContext.Current.Request.RawUrl;
// 例:/default/123.aspx → /default.aspx?id=123
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 (實體檔案不存在)。BeginRequest,Regex 比對成功。Context.RewritePath 將內部路徑改為 /default.aspx?id=123。default.aspx,Request.QueryString["id"] 取得 123。/default/123.aspx,達到 URL Rewrite 效果。/product/456/detail.aspx → /product.aspx?id=456&view=detail)。.myweb) 至 aspnet_isapi.dll,擴展至任意副檔名。Compiled 提升比對速度;規則過多建議改用 HttpModule 集中管理。