Asp.net URL重寫(URLRewriter)

來源:互聯網
上載者:User

可以使用 ISAPI 篩選器在 IIS Web 服務器層級實現 URL 重寫,也可以使用 HTTP 模組或 HTTP 處理常式在 ASP.NET 層級實現 URL 重寫。
在dotnet中如果實現URLRewriter只需做如下幾步:

第一步:添加dll引用 URLRewriter.dll

第二步:在web.config檔案中進行配置

先加入一個section節

<configuration>
    .......
  <configSections>
    <section name="RewriterConfig" type="URLRewriter.Config.RewriterConfigSerializerSectionHandler, URLRewriter"/>
  </configSections>

然後加入一個模組httpMoudles,

為 URL 重寫引擎指定配置資訊

<system.web>
。。。。。
<httpModules>
      <add type="URLRewriter.ModuleRewriter, URLRewriter" name="ModuleRewriter"/>
    </httpModules>

注意節的位置 

<system.web>與<configSections>兩個節是平級的

再加入規則<RewriterConfig>
      <Rules>
        <!-- Rules for Blog Content Displayer -->
        <RewriterRule>
          <LookFor>/ctrl/(.*).ashx</LookFor>
          <SendTo>/ControlContainer.aspx?control=/ctrl/$1.ascx</SendTo>
        </RewriterRule>
        <RewriterRule>
          <LookFor>ctrl/(.*).ashx</LookFor>
          <SendTo>/ControlContainer.aspx?control=ctrl/$1.ascx</SendTo>
        </RewriterRule>
      </Rules>
    </RewriterConfig>

這個節與<system.web>平級
注意sendto節中的路徑這塊設定不好,會報404錯誤的!
這裡的意思是凡是從路徑http://.../ctrl/111.ashx來的請求都由/ControlContainer.aspx?control=/ctrl/111.ascx來處理

除了指定使用 HTTP 模組還是 HTTP 處理常式執行重寫外,Web.config 檔案還包含重寫規則:重寫規則由兩個字串組成:要在被請求的 URL 中尋找的模式;要替換此模式的字串(如果找到)。在 Web.config 檔案中,此資訊是使用以下文法表達的:

<RewriterConfig><Rules><RewriterRule><LookFor>要尋找的模式</LookFor><SendTo>要用來替換模式的字串</SendTo></RewriterRule><RewriterRule><LookFor>要尋找的模式</LookFor><SendTo>要用來替換模式的字串</SendTo></RewriterRule>...</Rules></RewriterConfig>

每個重寫規則均由 <RewriterRule> 元素表達。要搜尋的模式由 <LookFor> 元素指定,而要替換所找到的模式的字串將在 <SentTo> 元素中輸入。這些重寫規則將從頭到尾進行計算。如果發現與某個規則匹配,URL 將被重寫,並且對重寫規則的搜尋將會終止。

在 <LookFor> 元素中指定模式時,請注意,要使用Regex來執行匹配和字串替換。(稍後,我們將介紹一個真實的樣本,說明如何使用Regex來搜尋模式。)由於模式是Regex,應確保轉義Regex中的任何保留字元。(一些Regex保留字元包括:.、?、^、$ 及其他。可以通過在前面加反斜線(如 \.)對這些字元進行轉義,以匹配文字句點。)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.