zoukankan      html  css  js  c++  java
  • 采用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注册。
  • 相关阅读:
    zTree学习笔记之展开树和收起树
    添优--史上超级全面的前端面试题大集合
    springboot2.0整合jpa
    Idea快捷键
    实用工具收藏
    nginx
    SQLServer锁的机制
    centos安装jenkins
    java8
    前端开发收藏
  • 原文地址:https://www.cnblogs.com/JinvidLiang/p/1962532.html
Copyright © 2011-2022 走看看