zoukankan      html  css  js  c++  java
  • 采用HttpModules来重写URLS


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

    public class UrlReWriteModule : System.Web.IHttpModule
    {
    public void Init(HttpApplication context)
    {
    context.BeginRequest +=new EventHandler(context_BeginRequest);
    }
    public void Dispose()
    {
    }
    }
    

      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/archive.aspx?user=rrooyy&id=56041 重写为 http://www.cnblogs.com/rrooyy/archive/2004/10/24/56041.。然后将重新生成的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);
    }
    

      最后要web.config中注册重写URLs的类,格式如下:

    <HTTPMODULES>
    <ADD type="classname,assemblyname" name="modulename"/>
    <REMOVE name="modulename"/>
    <CLEAR />
    </HTTPMODULES>
    


    ----

    在 Web 应用程序中添加模块。

    配置结构的示例:

    <configuration>
       <system.web>
          <httpModules>
             <add>


    语法

    <add name="ModuleName"
        type=".NET Class, Assembly [,Version=version number]
        [,Culture=culture] [,PublicKeyToken=token]"/>

    必需的属性

    属性描述
    name 给模块提供好记的名称。这可以使您将 Global.asax 文件中的模块事件与事件处理程序相关联。
    type 指定逗号分隔的类/程序集组合,它由版本号、区域性和公钥标记组成。ASP.NET 首先在应用程序的专用 Bin 目录中搜索程序集 DLL,然后在系统程序集缓存中搜索。

    注释

    <add> 指令按照从上到下的顺序进行处理。如果两个或多个 <add> 子标记指定相同的 verb/path 组合,则最后一个 <add> 覆盖所有其他子标记。

    示例

    下例在应用程序中添加模块。

    <configuration> <system.web> <httpModules> <add name="OutputCache" type="System.Web.Caching.OutputCacheModule, System.Web, Version=1.0.2800.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/> </httpModules> <system.web> </configuration>

    要求

    • 包含在:<system.web>
    • Web 平台:Internet 信息服务 (IIS) 5.0
    • 配置文件:Machine.config、Web.config
    • 配置节处理程序:System.Web.Configuration.HttpModulesConfigurationHandler
  • 相关阅读:
    14、Cahin of Responsibility 责任链 COR设计模式
    13、Visitor 访问者模式 访问数据结构并处理数据 行为型设计模式
    HTML inline 与block元素
    javascript 继承实现
    深入理解linux的权限设置和SUID,SGID以及粘滞位
    设置express ejs模板的后缀名html
    Centos 安装编译codeblocks&&codelite
    JavaScript中两种类型的全局对象/函数【转】
    Canvas vs. SVG[转]
    centos 学习总结
  • 原文地址:https://www.cnblogs.com/0515offer/p/4482526.html
Copyright © 2011-2022 走看看