使用 HTTP Module / Handler 實作 URL 重寫時,常遇到重寫後的進入頁面 (如空白 Default.aspx) 無法觸發 Session_Start,導致統計、購物車初始化等邏輯失效。根因:**重寫發生在 `HttpApplication.BeginRequest` 之後,`SessionStateModule` 尚未初始化 Session,導致重寫目標頁面未正確建立 Session 關聯。**
/EmptyDefault.aspx (空白頁面)EmptyDefault.aspx 再 `Server.Transfer` 或 `RewritePath` 至真實處理頁面Session_Start 不觸發,`Session.IsNewSession` 為 true 但 Session 內容為空自訂 `IHttpHandlerFactory` 或 `IHttpHandler` 時,**必須標記實作 `IRequiresSessionState` (或 `IReadOnlySessionState`)**,告知 ASP.NET 執行管線此 Handler 需要 Session 支援,管線會在執行 Handler 前正確初始化 Session 模組。
public class UrlRewriterFactory : IHttpHandlerFactory, IRequiresSessionState // 關鍵:加上此介面
{
public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
{
// 重寫邏輯
context.RewritePath("~/RealHandler.aspx", string.Empty, context.Request.QueryString.ToString());
return PageParser.GetCompiledPageInstance(url, context.Server.MapPath("~/RealHandler.aspx"), context);
}
public void ReleaseHandler(IHttpHandler handler) { }
}
<system.webServer> <!-- IIS 7+ 整合模式 -->
<modules>
<add name="UrlRewriteModule" type="MyApp.UrlRewriteModule" />
</modules>
<handlers>
<add name="UrlRewriter" verb="*" path="*.html"
type="MyApp.UrlRewriterFactory"
preCondition="integratedMode" />
</handlers>
</system.webServer>
<system.web> <!-- IIS 6 / 經典模式 -->
<httpHandlers>
<add verb="*" path="*.html" type="MyApp.UrlRewriterFactory" />
</httpHandlers>
<httpModules>
<add name="UrlRewriteModule" type="MyApp.UrlRewriteModule" />
</httpModules>
</system.web>
原文提到的附帶問題:`SqlParameter` 輸出 GUID 時長度被截斷為 1 字元。
// 錯誤:未指定 Size,預設可能為 1
var param = new SqlParameter("@UserId", SqlDbType.UniqueIdentifier) { Direction = ParameterDirection.Output };
// 正確:明確指定 Size = 36 (GUID 字串長度) 或不指定 (UniqueIdentifier 類型自動處理)
var param = new SqlParameter("@UserId", SqlDbType.UniqueIdentifier) { Direction = ParameterDirection.Output };
// 或
var param = new SqlParameter("@UserId", SqlDbType.NVarChar, 36) { Direction = ParameterDirection.Output };
SqlDbType.UniqueIdentifier 對應 `Guid`,不需指定 Size。SqlDbType.NVarChar 輸出 GUID 字串需 Size = 36。Size = 8000 導致效能浪費或錯誤。採用 IIS 原生 URL Rewrite Module 可徹底避開 Session 初始化時序問題,並簡化維護成本。