























这三个对象我们在开发Asp.net程序时经常会用到,似乎很熟悉,但有时候又不太确定。本文通过一个简单的例子来直观的比较一下这三个对象的使用。
HttpModule:Http模块,可以在页面处理前后、应用程序初始化、出错等时候加入自己的事件处理程序
HttpHandler:Http处理程序,处理页面请求
HttpHandlerFactory:用来创建Http处理程序,创建的同时可以附加自己的事件处理程序
例子很简单,就是在每个页面的头部加入一个版权声明。
一、HttpModule
这个对象我们经常用来进行统一的权限判断、日志等处理。
例子代码:
public class MyModule : IHttpModule
{
public void Init(HttpApplication application)
{
application.BeginRequest += new EventHandler(application_BeginRequest);
}

void application_BeginRequest(object sender, EventArgs e)
{
((HttpApplication)sender).Response.Write("Copyright @Gspring<br/>");
}

public void Dispose()
{
}
}
<httpModules>
<add name="test" type="HttpHandle.MyModule, HttpHandle"/>
</httpModules>
public class MyHandler : IHttpHandler
{
public void ProcessRequest(HttpContext ctx)
{
ctx.Response.Write("Copyright @Gspring<br/>");
}
public bool IsReusable
{
get { return true; }
}
}

<httpHandlers>
<add verb="*" path="*.aspx" type="HttpHandle.MyHandler, HttpHandle"/>
</httpHandlers>

<add path="*.aspx" verb="*" type="System.Web.UI.PageHandlerFactory" validate="true"/>
public class MyHandlerFactory : IHttpHandlerFactory
{
public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
{
PageHandlerFactory factory = (PageHandlerFactory)Activator.CreateInstance(typeof(PageHandlerFactory), true);
IHttpHandler handler = factory.GetHandler(context, requestType, url, pathTranslated);

//执行一些其它操作
Execute(handler);

return handler;
}

private void Execute(IHttpHandler handler)
{
if (handler is Page)
{
//可以直接对Page对象进行操作
((Page)handler).PreLoad += new EventHandler(MyHandlerFactory_PreLoad);
}
}

void MyHandlerFactory_PreLoad(object sender, EventArgs e)
{
((Page)sender).Response.Write("Copyright @Gspring<br/>");
}

public void ReleaseHandler(IHttpHandler handler)
{
}
}
<httpHandlers>
<add verb="*" path="*.aspx" type="HttpHandle.MyHandlerFactory, HttpHandle"/>
</httpHandlers>
<httpHandlers>
<add verb="*" path="*.spring" type="HttpHandle.MyHandlerFactory, HttpHandle"/>
</httpHandlers>
<compilation>
<buildProviders>
<add extension=".spring" type="System.Web.Compilation.PageBuildProvider"/>
</buildProviders>
</compilation>
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。