Server.Transfer 是伺服器端轉向,非 URL Rewrite(瀏覽器網址不變)。虛擬主機無法修改 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,瀏覽器網址列保持原狀,使用者無感知。
*.myweb),虛擬主機通常僅支援 .aspx 等已映射副檔名。