最近在交接,事情不多 所以就多逛逛园子,多研究一些以前没研究过的东西
要说IHttpModule 以前我也用到过 比如 Url重写 但那是别人写的dll 一直觉得那重写dll功能不太强 可是自己又不会
今天写了一个简单的示例 原理大概是明白了 估计以前再碰到url重写的问题 可以自己简单写个自己的dll来实现了
不多说了 贴代码 虽然是新手代码 也敢贴
IHttpModule 类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
namespace Test
{
class HttpModule : IHttpModule
{
#region IHttpModule 成员
public void Dispose()
{
}
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(BeginRequest);
context.EndRequest += new EventHandler(EndRequest);
}
void BeginRequest(object sender, EventArgs e)
{
HttpApplication http = sender as HttpApplication;
if (http.Context.Request.Url.OriginalString.IndexOf("/index.cc") != -1)
{
http.Context.Server.Transfer("default.aspx");
}
if (http.Context.Request.Form.Count > 3 || http.Context.Request.QueryString.Count > 0)
{
http.Context.Response.Write("哈哈!开始");
}
}
void EndRequest(object sender, EventArgs e)
{
HttpApplication http = sender as HttpApplication;
http.Context.Response.Write("哈哈!结束");
}
#endregion
}
}
web.config
<httpModules>
<add name="Test1" type="Test.HttpModel,Test"/>
</httpModules>
IHttpModule 和IHttpHandler 两者之间的区别在于
IHttpHandler 是完全替换页面本身的 类似于java中的servlet
IHttpModule 则是在页面之外进行操作 和页面本身没有任何关系
有点类似于设计模式中的适配器模式,把原来的页面包装一下
不知道我说的对不对