之前寫過 Asp.net Url改寫系列方法,今天看到另外一種方法。這裡轉過來。
文章來源:http://www.cnblogs.com/JinvidLiang/archive/2011/02/23/1962532.html
之前系列:
Asp.net Url改寫方法Asp.net Url改寫方法——回傳處理方法
Aspx改寫成Html尾碼方式的實現Asp.net Url改寫方法——使用Routing實現Asp.net Url改寫方法——採用HttpModules(轉)
採用HttpModules來重寫URLs
首先寫一個處理urls重寫的類,並且這個類必須繼承system.web.IHttpModule介面,以部落格園的程式為例:public class urlrewritemodule : System.Web.IHttpModule
{
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(context_BeginRequest);
}
public void Dispose()
{
//throw new NotImplementedException();
}
}
urlrewritemodule類就是處理urls重寫的類,繼承ihttphandler介面,實現該介面的兩個方法,init和dispose。在init方法裡註冊自己定義的方法,如上例所示:
content.beginrequest +=new eventhandler(content_beginrequest);
beginrequest是一個事件,在收到新的http請求時觸發,content_beginrequest就是觸發時處理的方法。另外說明一 點,httpmodules能註冊的方法還有很多,如:endrequest、error、disposed、 presendrequestcontent等等。
在content_beginrequest方法中具體處理urls重寫的細節,比如,將 http://www.cnblogs.com/rrooyy/archive/2004/10/24/56041.html 重寫為 http://www.cnblogs.com/archive.aspx?user=rrooyy&id=56041 (註:我沒有仔細看dudu的程式,這裡只是舉例而已)。然後將重建的url用httpcontext.rewritepath()方法重寫即可,如下:
void context_BeginRequest(object sender, EventArgs e)
{
HttpContext context = ((HttpApplication)sender).Context;
// 擷取舊的url
string url = context.request.path.tolower();
// 重建新的url
string newurl = "……"; // 具體過程略
// 重寫url
context.rewritepath(newurl);
}
提醒:newurl的格式不是http://www.infotouch.com/user/archive.aspx,而是從當前應用程式根目錄算起的絕對路徑,如:user\archive.aspx,這一點請特別注意。
最後要web.config中註冊重寫urls的類,格式如下:
<httpmodules>
<add type="classname,assemblyname" name="modulename"/>
<remove name="modulename"/>
<clear />
</httpmodules>
採用<add>標籤可以註冊一個類;<remove>可以移除某個類,如果某個子目錄不希望繼承父目錄的某個http module註冊,就需要使用這個標籤;<clear />可以移除所有的http module註冊。