Asp.NetURL重寫的一種方法

說到不用設置iis,主要是爲了實現在虛擬主機或是拿不到iis操作限的時候,不能添加isap又想實現類似於靜態化的程序實現方式,先聲明,這裏最終要實現的效果是,最終可以用

12345.html

替換

show.aspx?id=12345這樣的地址訪問

也可以實現百度空間的

http://hi.baidu.com/wu1987116

替換

http://hi.baidu.com/index.aspx?UserName=wu1987116

功能,支持任意擴展名及無擴展

程序要調整的部分只有兩塊。
一是web.config文件。
二是鏈接地址。
所需urlrewrite.dll

首先下載URLRewriter:http://download.microsoft.com/download/0/4/6/0463611e-a3f9-490d-a08c-877a83b797cf/MSDNURLRewriting.msi

下載安裝後再bin目錄下找到URLRewriter.dll文件

好了開始實施。
第一步:將urlrewrite.dll下載到你的web程序目錄裏去。哪都行。我是放在bin裏面的。然後添加引用,將urlrewrite.dll引用進來。
第二步:修改web.config
這一步要修改幾個地方。要注意位置是不同的

1 在web.config文件中加入如下代碼,注意要放在<configuration>下面, <appSettings/>
<connectionStrings/> <system.web>上面不然會出錯

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

其中

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

用於指定配置節"RewriterConfig"的處理程序類的名稱爲”URLRewriter.Config.RewriterConfigSerializerSectionHandler”,該類存在於bin目錄下的URLRewriter.dll文件中

2 在web.config文件中的system.web節點下加入如下代碼

<httpHandlers>
<add verb="*" path="*.html"
type
="URLRewriter.RewriterFactoryHandler, URLRewriter" />
<add verb="*" path="*"
type
="URLRewriter.RewriterFactoryHandler, URLRewriter" />
</httpHandlers>

這段代碼的意思是:將文件擴展名爲.html和任意擴展名(包括無擴展名,不包括*.html,因爲這個位置在上面會先處理)的文件的所有 HTTP 請求映射到類 URLRewriter.RewriterFactoryHandler,注意順序,按從上到下執行,如果path="*"在上面的話,則下面的html映射則無效,下面步驟中有映射到那個頁面的設置

3 重寫url

和1一樣 ,同樣是放在<configuration>節點下面

關鍵就是

複製代碼
<RewriterConfig>
<Rules>
<RewriterRule>
<LookFor>~/(.+).html</LookFor>
<SendTo>~/Shownews.aspx?ShowID=$1</SendTo>
</RewriterRule>
<RewriterRule>
<LookFor>~/(.+)</LookFor>
<SendTo>~/blog.aspx?UserName=$1</SendTo>
</RewriterRule>
</Rules>
</RewriterConfig>
複製代碼

效果:當訪問http://127.0.0.1/123.html時,實際訪問的是http://127.0.0.1/Shownews.aspx?ShowID=123

訪問http://127.0.0.1/任意字符時,實際訪問的是http://127.0.0.1/blog.aspx?UserName=任意字符

注意第2,3步中的映射順序

其中關鍵在url的轉換

<LookFor>~/(.+).html</LookFor>

<SendTo>~/Shownews.aspx?ShowID=$1</SendTo>

意思是把第一個路徑轉成另一個路徑。其中<LookFor>()中的正則表達式就是第二句中的參數$1 .

同樣也可以用$2 $3來表示<LookFor>中第二 第三個()中的參數。

多個參數:

<ReWriterUrls>
<rule>
<old>(.*)/TestUrlRe/file(.*)/(.*)\.html</old>
<new>../WebForm1.aspx?id=$2&amp;type=$3</new>
</rule>
<rule>
<old>(.*)/TestUrlRe/t(.*)/(.*)\.html</old>
<new>../WebForm1.aspx?tid=$2&amp;ttype=$3</new>
</rule>
</ReWriterUrls>

第三步:在頁面程序中可以這樣寫:
<a href="news_<%=newsid%>.html" target="_blank">新聞標題</a>

完成上面三個步驟就可以輕鬆實現URL重寫了,不過需要注意的是:如果發佈網站的話,你會發現你的URL重寫有可能會失效,如果失效的話就需要您設置一下IIS:
打開IIS,主目錄-〉配置-〉映射-〉點擊“插入”通配符應用程序映射-〉選擇“C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll”,然後把勾選去掉(一定要去掉),然後確定。
上面設置完畢之後,就可以正常瀏覽了。

發佈了26 篇原創文章 · 獲贊 1 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章