在 asp.net 里實(shí)現(xiàn) URL重寫(URLRewriter)的一個(gè)最簡單的方法。
參考了 (作者 Scott Mitchell 翻譯:Janssen )的大作,雖然沒有完全看明白,但是也照貓畫虎地做了一個(gè),頗有“成就”感。寫出來分享一下。
原作里講了很多的原理,這里就不說了(其實(shí)我也不懂)。這里就寫操作過程吧。目的是實(shí)現(xiàn)一個(gè)最簡單的能實(shí)現(xiàn) URL重寫 的程序。
1、需要設(shè)置一下IIS里的站點(diǎn)屬性。
2、修改web.config的內(nèi)容。
<system.web>
<httpHandlers>
<add verb="*" path="*.zhtml" type="ZDIL.URLRewriter.RewriterFactoryHandler, ZDILURLRewriter" />
</httpHandlers>
</system.web>
其中*.zhtml 就是地址欄里面寫的網(wǎng)頁的擴(kuò)展名,就是給用戶看的,這個(gè)可以隨意改(但是要符合擴(kuò)展名的規(guī)則!)。當(dāng)然要和第一步里面的設(shè)置相一致才行。
3、寫一個(gè)類。
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 = ""; //參數(shù)。比如 ?id=123
filePath = context.Server.MapPath(sendToURLString); //物理地址
//這句最重要了。轉(zhuǎn)向了。
context.RewritePath(sendToURLString, String.Empty, queryString);
//這個(gè)還沒有弄明白 :)
return PageParser.GetCompiledPageInstance(url, filePath, context);
}
public virtual void ReleaseHandler(IHttpHandler handler)
{ //這個(gè)也不懂了
}
}
}
這個(gè)類呢,要寫在一個(gè)單獨(dú)的項(xiàng)目里面,然后編譯成 ZDILURLRewriter.DLL文件。(注意文件名,寫錯(cuò)了就不能正常運(yùn)行了)。
4、完成了。
打開IE ,在地址欄里輸入 http://.../1.zhtml。
瀏覽者看到是一個(gè)靜態(tài)頁的地址,但是實(shí)際上訪問的卻是 /web/index.aspx 這個(gè)動(dòng)態(tài)網(wǎng)頁。
怎么樣簡單吧。
當(dāng)然了,這個(gè)是最簡單的,簡單到了“不能用”的地步了。因?yàn)樗麜?huì)把所有的 *.zhtml 的訪問都“重寫”到 /web/index.aspx 。
至于把什么樣的網(wǎng)頁重寫到哪個(gè)網(wǎng)頁,這里就不介紹了(這里只講方法,不講實(shí)現(xiàn)的細(xì)節(jié))。
方法很多了,原作是通過正則來匹配的,我是通過 string sendToUrl = url; 來判斷的。
其他的就看你們的需要了。
http://blog.csdn.net/shixin1198/archive/2006/10/16/1336846.aspx
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注