采用HttpModules来重写URLs(实践篇)

本文介绍如何在ASP.NET中实现URL重写,通过创建一个继承自IHttpModule的类来处理URL重写逻辑。文章详细解释了如何注册自定义处理方法并在HTTP请求开始时触发,同时展示了如何使用HttpContext.RewritePath方法来修改URL。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先写一个处理urls重写的类,并且这个类必须继承ihttpmodule接口,以博客园的程序为例:

public class urlrewritemodule : system.web.ihttpmodule
{
public void init(httpapplication context)
{
context.beginrequest +=new eventhandler(context_beginrequest);
}

public void dispose()
{
}
}

urlrewritemodule类就是处理urls重写的类,继承ihttpmodule接口,实现该接口的两个方法,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()方法重写即可,如下:

private 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注册。

转载于:https://www.cnblogs.com/JinvidLiang/archive/2011/02/23/1962532.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值