在 asp.net 里實現 url重寫(urlrewriter)的一個最簡單的方法。
參考了 (作者 scott mitchell 翻譯:janssen )的大作,雖然沒有完全看明白,但是也照貓畫虎地做了一個,頗有“成就”感。寫出來分享一下。
原作里講了很多的原理,這里就不說了(其實我也不懂)。這里就寫操作過程吧。目的是實現一個最簡單的能實現 url重寫 的程序。
1、需要設置一下iis里的站點屬性。
2、修改web.config的內容。
<system.web>
<httphandlers>
<add verb="*" path="*.zhtml" type="zdil.urlrewriter.rewriterfactoryhandler, zdilurlrewriter" />
</httphandlers>
</system.web>
其中*.zhtml 就是地址欄里面寫的網頁的擴展名,就是給用戶看的,這個可以隨意改(但是要符合擴展名的規則!)。當然要和第一步里面的設置相一致才行。
3、寫一個類。
using system;
using system.io;
using system.web;
using system.web.ui;
namespace zdil.urlrewriter
{
/**//// <summary>
/// url重寫
/// </summary>
public class rewriterfactoryhandler : ihttphandlerfactory
{
/**//// <summary>
/// gethandler is executed by the asp.net pipeline after the associated httpmodules have run. the job of
/// gethandler is to return an instance of an httphandler that can process the page.
/// </summary>
/// <param name="context">the httpcontext for this request.</param>
/// <param name="requesttype">the http data transfer method (<b>get</b> or <b>post</b>)</param>
/// <param name="url">the rawurl of the requested resource.</param>
/// <param name="pathtranslated">the physical path to the requested resource.</param>
/// <returns>an instance that implements ihttphandler; specifically, an httphandler instance returned
/// by the <b>pageparser</b> class, which is the same class that the default asp.net pagehandlerfactory delegates
/// to.</returns>
public virtual ihttphandler gethandler(httpcontext context, string requesttype, string url, string pathtranslated)
{
string sendtourl = url; //地址欄里面的地址
string filepath = pathtranslated;
string sendtourlstring = "/web/index.aspx"; //真正要訪問的頁面
string querystring = ""; //參數。比如 ?id=123
filepath = context.server.mappath(sendtourlstring); //物理地址
//這句最重要了。轉向了。
context.rewritepath(sendtourlstring, string.empty, querystring);
//這個還沒有弄明白 :)
return pageparser.getcompiledpageinstance(url, filepath, context);
}
public virtual void releasehandler(ihttphandler handler)
{ //這個也不懂了
}
}
}
這個類呢,要寫在一個單獨的項目里面,然后編譯成 zdilurlrewriter.dll文件。(注意文件名,寫錯了就不能正常運行了)。
4、完成了。
打開ie ,在地址欄里輸入 http://.../1.zhtml。
瀏覽者看到是一個靜態頁的地址,但是實際上訪問的卻是 /web/index.aspx 這個動態網頁。
怎么樣簡單吧。
當然了,這個是最簡單的,簡單到了“不能用”的地步了。因為他會把所有的 *.zhtml 的訪問都“重寫”到 /web/index.aspx 。
至于把什么樣的網頁重寫到哪個網頁,這里就不介紹了(這里只講方法,不講實現的細節)。
方法很多了,原作是通過正則來匹配的,我是通過 string sendtourl = url; 來判斷的。
其他的就看你們的需要了。
新聞熱點
疑難解答
圖片精選