最近在看HttpHandler映射过程文章时发现Context对象中有一个RemapHandler方法,它能将当前请求映射到指定的HttpHandler处理,可跳过系统默认的Httphandler。它的好处是我们可以在代码中根据需求动态的指定HttpHandler。个人觉得挺好用,就分享给大家。
通过.net 反编译工具看到获取HttpHandler的方法,关键代码如下:
internal IHttpHandler MapHttpHandler(HttpContext context, string requestType,
VirtualPath path, string pathTranslated, bool useAppConfig)
{
IHttpHandler handler = (context.ServerExecuteDepth == 0) ? context.RemapHandlerInstance : null;
using( new ApplicationImpersonationContext() ) {
if( handler != null )
return handler;
HttpHandlerAction mapping = this.GetHandlerMapping(context, requestType, path, useAppConfig);
if( mapping == null )
throw new HttpException("Http_handler_not_found_for_request_type");
IHttpHandlerFactory factory = this.GetFactory(mapping);
IHttpHandlerFactory2 factory2 = factory as IHttpHandlerFactory2;
if( factory2 != null )
handler = factory2.GetHandler(context, requestType, path, pathTranslated);
else
handler = factory.GetHandler(context, requestType, path.VirtualPathString, pathTranslated);
this._handlerRecycleList.Add(new HandlerWithFactory(handler, factory));
}
return handler;
}
我们来看这段:
IHttpHandler handler = (context.ServerExecuteDepth == 0) ? context.RemapHandlerInstance : null;
using( new ApplicationImpersonationContext() ) {
if( handler != null )//如果调用了HttpContext.RemapHttpHandler方法,则直接返回设置的HttpHandler对象,跳过后面获取系统默认的HttpHandler处理程序
return handler;
如果之前调用了HttpContext.RemapHttpHandler()方法,则返回Context.RemapHandlerInstance,即RemapHttpHandler方法指定的HttpHandler实例。
实例:
Global.asax中的Application_BeginRequest事件中指定自定义的TestHandler类
public class Global : System.Web.HttpApplication
{
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
app.Context.RemapHandler(new TestHandler());
}
}
TestHandler.cs
public class TestHandler:IHttpHandler
{
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
context.Response.Write("TestHandler");
}
}
Default.aspx
<body>
<form id="form1" runat="server">
<div>
Default.aspx
</div>
</form>
</body>
在网址中输入请求Default.aspx,响应结果:
可以看出,系统调用了自定义的TestHandler,没有执行Default.aspx页面