您的位置:首页 > 理论基础 > 计算机网络

采用HttpModules来重写URLS

2015-05-06 16:57 197 查看
首先写一个处理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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: