程序要調(diào)整的部分只有兩塊。
一是web.config文件。
二是鏈接地址。
所需urlrewrite.dll
首先下載URLRewriter:http://download.microsoft.com/download/0/4/6/0463611e-a3f9-490d-a08c-877a83b797cf/MSDNURLRewriting.msi
下載安裝后再bin目錄下找到URLRewriter.dll文件
好了開始實(shí)施。
第一步:將urlrewrite.dll下載到你的web程序目錄里去。哪都行。我是放在bin里面的。然后添加引用,將urlrewrite.dll引用進(jìn)來。
第二步:修改web.config
這一步要修改幾個(gè)地方。要注意位置是不同的
1 在web.config文件中加入如下代碼,注意要放在<configuration>下面, <appSettings/>
<connectionStrings/> <system.web>上面不然會出錯(cuò)
<configSections>
<section name="RewriterConfig"type="URLRewriter.Config.RewriterConfigSerializerSectionHandler, URLRewriter" />
</configSections>
其中
<section name="RewriterConfig"
type="URLRewriter.Config.RewriterConfigSerializerSectionHandler, URLRewriter" />
用于指定配置節(jié)"RewriterConfig"的處理程序類的名稱為”URLRewriter.Config.RewriterConfigSerializerSectionHandler”,該類存在于bin目錄下的URLRewriter.dll文件中
2 在web.config文件中的system.web節(jié)點(diǎn)下加入如下代碼
<httpHandlers>
<add verb="*" path="*.html"
type="URLRewriter.RewriterFactoryHandler, URLRewriter" />
<add verb="*" path="*"
type="URLRewriter.RewriterFactoryHandler, URLRewriter" />
</httpHandlers>
這段代碼的意思是:將文件擴(kuò)展名為.html和任意擴(kuò)展名(包括無擴(kuò)展名,不包括*.html,因?yàn)檫@個(gè)位置在上面會先處理)的文件的所有 HTTP 請求映射到類 URLRewriter.RewriterFactoryHandler,注意順序,按從上到下執(zhí)行,如果path="*"在上面的話,則下面的html映射則無效,下面步驟中有映射到那個(gè)頁面的設(shè)置
3 重寫url
和1一樣 ,同樣是放在<configuration>節(jié)點(diǎn)下面
關(guān)鍵就是
<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>
效果:當(dāng)訪問http://127.0.0.1/123.html時(shí),實(shí)際訪問的是http://127.0.0.1/Shownews.aspx?ShowID=123
訪問http://127.0.0.1/任意字符時(shí),實(shí)際訪問的是http://127.0.0.1/blog.aspx?UserName=任意字符
注意第2,3步中的映射順序
其中關(guān)鍵在url的轉(zhuǎn)換
<LookFor>~/(.+).html</LookFor>
<SendTo>~/Shownews.aspx?ShowID=$1</SendTo>
意思是把第一個(gè)路徑轉(zhuǎn)成另一個(gè)路徑。其中<LookFor>()中的正則表達(dá)式就是第二句中的參數(shù)$1 .
同樣也可以用$2 $3來表示<LookFor>中第二 第三個(gè)()中的參數(shù)。
多個(gè)參數(shù):
<ReWriterUrls>
<rule>
<old>(.*)/TestUrlRe/file(.*)/(.*)\.html</old>
<new>../WebForm1.aspx?id=$2&type=$3</new>
</rule>
<rule>
<old>(.*)/TestUrlRe/t(.*)/(.*)\.html</old>
<new>../WebForm1.aspx?tid=$2&ttype=$3</new>
</rule>
</ReWriterUrls>
第三步:在頁面程序中可以這樣寫:
<a href="news_<%=newsid%>.html" target="_blank">新聞標(biāo)題</a>
完成上面三個(gè)步驟就可以輕松實(shí)現(xiàn)URL重寫了,不過需要注意的是:如果發(fā)布網(wǎng)站的話,你會發(fā)現(xiàn)你的URL重寫有可能會失效,如果失效的話就需要您設(shè)置一下IIS:
打開IIS,主目錄-〉配置-〉映射-〉點(diǎn)擊“插入”通配符應(yīng)用程序映射-〉選擇“C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll”,然后把勾選去掉(一定要去掉),然后確定。
上面設(shè)置完畢之后,就可以正常瀏覽了。