萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP.NET URL Rewrite 完整實作教學 (URLRewriter)

本文與前一篇 (ID 67457) 內容高度重複,均為使用 URLRewriter.dll 實現無需 IIS 設定的 URL 重寫。此處補充更多實務細節與常見問題排查。

核心步驟回顧

  1. 引用 URLRewriter.dll。
  2. Web.config 註冊 <configSections>、<httpHandlers>、<RewriterConfig> 三區塊。
  3. 前端連結寫成靜態風格 (如 news_123.html)。

常見坑點與解決

現象原因對策
重寫不生效、直接 404IIS 未將 .html 對應至 ASP.NET加入萬用字元對應至 aspnet_isapi.dll 並取消「驗證檔案存在」
規則順序錯誤導致錯誤對應path="*" 在 path="*.html" 之前調整 <httpHandlers> 順序,特定副檔名優先
CSS/JS/圖片 404靜態資源也被重寫規則攔截規則加入排除:<LookFor>~/(?!.*\.(css|js|png|jpg|gif)).+\.html</LookFor>
PostBack 後網址變回 .aspxForm action 未重寫使用 form.Action = Request.RawUrl 或 Control Adapter 修正

進階:多參數與多規則

<RewriterConfig>
  <Rules>
    <!-- 產品頁 -->
    <RewriterRule>
      <LookFor>~/product/(\d+)/(\w+)\.html</LookFor>
      <SendTo>~/ProductDetail.aspx?Id=$1&Category=$2</SendTo>
    </RewriterRule>
    <!-- 使用者個人頁 -->
    <RewriterRule>
      <LookFor>~/user/([\w-]+)</LookFor>
      <SendTo>~/Profile.aspx?Name=$1</SendTo>
    </RewriterRule>
  </Rules>
</RewriterConfig>

現代替代方案

  • ASP.NET Routing (Web Forms 4.0+ / MVC) — 內建、效能佳、支援雙向路由 (產生連結)。
  • IIS URL Rewrite Module — 若有 IIS 管理權限,設定於 web.config <system.webServer>/<rewrite>,效能更高且不影響 ASP.NET 管線。
  • ASP.NET Core — 內建 Endpoint Routing,完全取代舊式重寫。
copyright © 萬盛學電腦網 all rights reserved