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

ASP.NET 偽靜態 URL Rewriter 完整設定指南(web.config)

     編輯:ASP.NET 基礎

核心步驟三部曲

  1. 註冊重寫模組(<configSections>)
  2. 定義重寫規則(<RewriterConfig>)
  3. 對應 HTTP 處理常式(<httpHandlers> / <system.webServer><handlers>)

完整 web.config 範例

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <!-- 1. 註冊區段處理器 -->
  <configSections>
    <section name="RewriterConfig"
             type="URLRewriter.Config.RewriterConfigSerializerSectionHandler, URLRewriter" />
  </configSections>

  <!-- 2. 重寫規則 -->
  <RewriterConfig>
    <Rules>
      <!-- news.aspx?id=1&pid=2  →  /news/1/2.html -->
      <RewriterRule>
        <LookFor>~/news/(.[0-9]*)/(.[\d]*)\.html</LookFor>
        <SendTo><![CDATA[~/news.aspx?id=$1&pid=$2]]></SendTo>
      </RewriterRule>
      <!-- product.aspx?pid=123  →  /product/123.zangdalei -->
      <RewriterRule>
        <LookFor>~/product/(.[\d]*)\.zangdalei</LookFor>
        <SendTo><![CDATA[~/product.aspx?pid=$1]]></SendTo>
      </RewriterRule>
    </Rules>
  </RewriterConfig>

  <system.web>
    <compilation debug="false" targetFramework="4.0">
      <!-- 避免真實 .html 被編譯 -->
      <buildProviders>
        <add extension=".html" type="System.Web.Compilation.PageBuildProvider" />
      </buildProviders>
    </compilation>

    <!-- 3. IIS 6 / Classic 模式處理常式 -->
    <httpHandlers>
      <add verb="*" path="*.html"       type="URLRewriter.RewriterFactoryHandler, URLRewriter" />
      <add verb="*" path="*.zangdalei" type="URLRewriter.RewriterFactoryHandler, URLRewriter" />
    </httpHandlers>
  </system.web>

  <!-- 3. IIS 7+ 整合模式處理常式 -->
  <system.webServer>
    <handlers>
      <add name="aspnet_html"    path="*.html"       verb="GET,POST"
           modules="IsapiModule" scriptProcessor="C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll"
           resourceType="Unspecified" preCondition="classicMode,runtimeVersionv4.0,bitness32" />
      <add name="aspnet_zangdalei" path="*.zangdalei" verb="GET,POST"
           modules="IsapiModule" scriptProcessor="C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll"
           resourceType="Unspecified" preCondition="classicMode,runtimeVersionv4.0,bitness32" />
    </handlers>
    <defaultDocument>
      <files><clear /><add value="default.aspx" /><add value="default.html" /></files>
    </defaultDocument>
  </system.webServer>
</configuration>

關鍵細節說明

  • LookFor 使用正則捕捉群組 $1、$2 對應 SendTo 參數。
  • buildProviders 註冊 .html 交由 PageBuildProvider,防止真實靜態頁面被誤重寫。
  • IIS 7+ 需在 <system.webServer><handlers> 註冊 ISAPI 對應,preCondition 依環境調整(Classic/Integrated、x86/x64)。
  • 需引用 URLRewriter.dll 並置於 bin 目錄。

現代替代方案

ASP.NET Core / .NET 5+ 建議使用內建 Endpoint Routing 或 Microsoft.AspNetCore.Rewrite 中介軟體,無需額外 DLL,支援更豐富的規則語法與中介軟體管線整合。

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