許多開發者為實現二級域名 (如 user1.site.com) 而引入第三方組件,實際上 ASP.NET 內建 IHttpModule 機制即可完美支援。本文展示如何攔截請求、解析子域名、重寫路徑,實現無組件依賴的偽靜態路由。
ASP.NET 請求生命週期中,每個請求會建立獨立的 HttpContext 實例。實作 IHttpModule 介面的 Init(HttpApplication context) 方法,掛載 BeginRequest 事件,即可在管線早期介入 URL 重寫。
public class URLRewriter : IHttpModule
{
public void Init(HttpApplication app)
{
app.BeginRequest += OnBeginRequest;
}
private void OnBeginRequest(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
HttpContext context = app.Context;
string url = context.Request.Url.AbsoluteUri; // 完整 URL
// 解析子域名 (假設格式: sub.domain.com)
string host = context.Request.Url.Host;
string[] parts = host.Split('.');
if (parts.Length >= 3) // 至少三段: sub + domain + tld
{
string subDomain = parts[0].ToLower();
// 排除 www 等常見前綴
if (subDomain != "www")
{
// 重寫路徑: /User/Index?sub=xxx
string newPath = $"/User/Index?sub={subDomain}";
context.RewritePath(newPath);
}
}
}
public void Dispose() { }
}
<system.web>
<httpModules>
<add name="URLRewriter" type="Common.URLRewriter" />
</httpModules>
</system.web>
<!-- IIS 7+ 整合管線模式 -->
<system.webServer>
<modules>
<add name="URLRewriter" type="Common.URLRewriter" />
</modules>
</system.webServer>
*.domain.com 指向伺服器 IP。Integrated 管線模式。RouteTable.Routes) 實現更靈活的 MVC/WebForms 統一路由。此方案完全基於 .NET Framework 內建機制,無第三方依賴,掌握核心管線即可靈活擴展,是理解 ASP.NET 請求處理的絕佳實踐案例。