需要继承System.Web.IHttpModule接口。该接口只有两个方法:System.Web.IHttpModule.Dispose()和System.Web.IHttpModule.Init(System.Web.HttpApplication)

啥都不说了,贴代码:

namespace RequestModuleNS
{
public class RequestModuleClass: IHttpModule
{

public void Dispose()
{
//clean-up code here.
}

public void Init(HttpApplication app)
{
app.BeginRequest += new EventHandler(app_BeginRequest);
app.EndRequest += new EventHandler(app_EndRequest);
}

void app_EndRequest(object sender, EventArgs e)
{
HttpApplication app
= sender as HttpApplication;
if (app.Request.Cookies.Get("Cookie1") == null)
{
return;
}
       ..............
}

void app_BeginRequest(object sender, EventArgs e)
{
HttpApplication app
= sender as HttpApplication;
string videoId = app.Request.QueryString["elementId"];
string requestUrl = app.Request.Url.ToString();
app.Request.Cookies.Add(
new HttpCookie("Cookie1", "Just A Test"));
        try
{
          
//Test to see if the duplicate cookie can be added. The result shows no error pops up.
app.Request.Cookies.
Add(new HttpCookie("Cookie1", "Just A Test to Override"));
       }
catch (Exception ex)
{
}
}
#endregion
}
}

我的启示:

1) HttpApplication对象是Asp.net内部生成并分给应用程序的。但是因为HttpApplication一次只能处理一个请求,所以避免了并发的很多麻烦。

2)每个HttpModule对每个request都是单例的,也就是说,在HttpModule里定义的全局变量是所以request共享的,所以不要把每个request自己的参数定义在HttpModule里。在我的代码里,把要保存的变量放在了HttpApplication.Request.Cookies里,可是只能存string类型。

3)HttpApplication.Request.Cookies重复添加相同名字的HttpCookie对象,直接覆盖,不会报错。

posted on 2011-08-11 17:15  linpiner  阅读(286)  评论(0)    收藏  举报