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


首先写一个处理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注册。
优质内容筛选与推荐>>
1、HDU 5396 区间DP 数学 Expression
2、ECSHOP 商品详情页 购物车页 添加购买数量加减按钮
3、ch6对抗搜索
4、php学习笔记之--函数的声明与应用
5、github clone速度太慢问题


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号