HttpHandlers、HttpModules介绍
HttpHandlers 和 HttpModules 通过扩展原始的页面框架,提供了用于处理请求和响应的两种途径。HttpHanders的主要目的是处理对某种特定文件或者在URL中对某个文件路径的请求,而HttpModule则主要被用于在最开始的阶段处理一个请求以及在最后阶段处理一个响应。
HttpHandlers介绍
HttpHandlers是指实现了IHttpHandler接口的类。它们在ProcessRequest()方法中获得对当前HttpContext 对象的引用,并能依靠HttpContext对象的属性来执行代码。典型的例子是,HttpHandler分析来自Request属性(对象)的数据并通过Response属性发送回某些东西。HttpHandler同时实现了一个IsReusable属性,它告诉Asp.net是否类的同一个实例能够用于处理并发(subsequent)的请求。
通过实现IHttpHandler接口实例化HttpHandler
namespace jwtLib
{
public class JwtHandler : IHttpHandler
{
public bool IsReusable
{
get { return false; }
}
public void ProcessRequest(HttpContext context)
{
context.Response.Write("这是来至JwtHandler的输出信息!");
}
}
}
<httpHandlers>
<add verb="*" path="*.aspx" type="jwtLib.JwtHandler.jwtLi"/>
</httpHandlers>
通过实现IHttpHandlerFactory实例化HttpHandler
public class JwtHandler2 : IHttpHandlerFactory
{
public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
{
string className = "jwtLib. JwtHandler";
object h = null;
try
{
h = Activator.CreateInstance(Type.GetType(className));
}
catch (Exception e)
{
throw new HttpException("不能为类型" + className + "创建实例。", e);
}
return (IHttpHandler)h;
}
public void ReleaseHandler(IHttpHandler handler)
{ }
}
<httpHandlers>
<add verb="*" path="*.aspx" type="jwtLib.JwtHandler2.jwtLi"/>
</httpHandlers>
HttpModules介绍
HttpModules通过添加事件处理器到应用程序的事件,从而代码可以同应用程序进行交互。这些类都必须实现IHttpModule接口。 Init()方法为我们提供了对一个应用程序的引用,在那个方法中我们可以绑定事件处理器到应用程序的事件上。事件处理器通过实现基本的事件处理器标记式 来同应用程序进行交互。HttpModule也实现了一个Dispose()方法,它被用于在应用程序结束时执行必需的清理工作。
namespace jwtLib
{
public class JwtModules : IHttpModule
{
public void Init(HttpApplication context)
{
context.Context.Cache["a"] = "a";
}
public void Dispose()
{
}
}
}
<httpModules>
<add name="Cash" type="jwtLib.JwtModules,jwtLib"/>
</httpModules>