阿宽

Nothing is more powerful than habit!
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Asp.net Url改写方法——采用HttpModules(转)

Posted on 2011-02-24 09:15  宽田  阅读(398)  评论(0编辑  收藏  举报

之前写过 Asp.net Url改写系列方法,今天看到另外一种方法。这里转过来。

文章来源:http://www.cnblogs.com/JinvidLiang/archive/2011/02/23/1962532.html

 

之前系列:

 

 

采用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注册。