可以使用 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保留字元包括:.、?、^、$ 及其他。可以通過在前面加反斜線(如 \.)對這些字元進行轉義,以匹配文字句點。)