ASP.NET 處理管線允許透過實作 IHttpHandlerFactory 攔截特定副檔名請求,並在 GetHandler 中以 context.RewritePath 將公開 URL 重寫為內部實體頁面,達到「靜態化 URL」與「隱藏真實路徑」的效果。
.zhtml 指向 aspnet_isapi.dll,勾選「驗證檔案是否存在」取消。web.config <system.webServer><handlers> 註冊即可,無須 IIS 介面操作。<system.web>
<httpHandlers>
<add verb="*" path="*.zhtml" type="ZDIL.URLRewriter.RewriterFactoryHandler, ZDILURLRewriter" />
</httpHandlers>
</system.web>
ZDILURLRewriter 為編譯後的 DLL 檔名 (不含副檔名)。
using System;
using System.Web;
using System.Web.UI;
namespace ZDIL.URLRewriter
{
public class RewriterFactoryHandler : IHttpHandlerFactory
{
public virtual IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
{
string sendToUrl = url; // 瀏覽器請求的虛擬路徑 (如 /product/123.zhtml)
string targetUrl = "/web/index.aspx"; // 真正處理的內部頁面
string queryString = ""; // 可解析 sendToUrl 擷取參數
string filePath = context.Server.MapPath(targetUrl);
// 核心:重寫路徑,保持瀏覽器網址列不變
context.RewritePath(targetUrl, String.Empty, queryString);
// 回傳編譯後的頁面實例
return PageParser.GetCompiledPageInstance(url, filePath, context);
}
public virtual void ReleaseHandler(IHttpHandler handler) { }
}
}
public virtual IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
{
string sendToUrl = url;
string targetUrl = "/web/index.aspx";
string queryString = "";
// 範例:/product/123.zhtml → /web/index.aspx?cat=product&id=123
var match = System.Text.RegularExpressions.Regex.Match(sendToUrl, @"/(?<cat>\w+)/(?<id>\d+)\.zhtml$");
if (match.Success)
{
queryString = $"cat={match.Groups["cat"].Value}&id={match.Groups["id"].Value}";
}
string filePath = context.Server.MapPath(targetUrl);
context.RewritePath(targetUrl, String.Empty, queryString);
return PageParser.GetCompiledPageInstance(url, filePath, context);
}
| 優點 | 缺點 |
|---|---|
| 無需第三方元件,純 .NET Framework 實作 | 需編譯獨立 DLL,部署稍繁瑣 |
| 完全控制重寫邏輯,支援正則/查表 | 舊版 IIS 需設定萬用字元對應 |
| 效能優於 HttpModule + Response.Redirect | 不支援 IIS 7+ 整合模式原生模組優勢 |
System.Web.Routing (Web Forms Routing) 或 UrlRoutingModule。MapControllerRoute、MapRazorPages。URL Rewrite Module (web.config <rewrite> 規則),無需撰寫代碼。