Asp.net Url改寫方法——採用HttpModules)

來源:互聯網
上載者:User

之前寫過 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註冊。

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.