首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET URL 重寫導致 Session_Start 不觸發問題解決

     編輯:關於ASP.NET

使用 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 內容為空

解決方案:實作 IRequiresSessionState 介面

自訂 `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) { }
}

Web.config 註冊


<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>

補充:SQL 輸出參數 GUID 長度問題

原文提到的附帶問題:`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 導致效能浪費或錯誤。

URL 重寫最佳實務總結

  1. **優先使用 IIS URL Rewrite Module 2.0** (Web.config `` 規則),無需寫代碼、效能最好、支援輸出快取、完美相容 Session。
  2. 若必須自訂 Handler/Module,**務必實作 `IRequiresSessionState`**。
  3. 重寫邏輯放在 `BeginRequest` (Module) 或 `GetHandler` (Factory) 中。
  4. 避免 `Server.Transfer` 導致路徑混淆,改用 `context.RewritePath`。
  5. 靜態資源 (.css, .js, .png) 排除重寫規則 (``)。

採用 IIS 原生 URL Rewrite Module 可徹底避開 Session 初始化時序問題,並簡化維護成本。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved