Asp.Net HttpContext.RemapHandler 用法
2015-06-12 09:45
706 查看
最近在看HttpHandler映射过程文章时发现Context对象中有一个RemapHandler方法,它能将当前请求映射到指定的HttpHandler处理,可跳过系统默认的Httphandler。它的好处是我们可以在代码中根据需求动态的指定HttpHandler。个人觉得挺好用,就分享给大家。
通过.net 反编译工具看到获取HttpHandler的方法,关键代码如下:
我们来看这段:
如果之前调用了HttpContext.RemapHttpHandler()方法,则返回Context.RemapHandlerInstance,即RemapHttpHandler方法指定的HttpHandler实例。
实例:
Global.asax中的Application_BeginRequest事件中指定自定义的TestHandler类
TestHandler.cs
Default.aspx
在网址中输入请求Default.aspx,响应结果:
可以看出,系统调用了自定义的TestHandler,没有执行Default.aspx页面
通过.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页面
相关文章推荐
- android 项目中使用到的网络请求框架以及如何配置好接口URL
- TCP3次握手和backlog溢出
- linux网络配置相关文件
- Android studio更新提示网络问题
- linux网络配置相关命令、虚拟网络接口eth0:0
- http协议总结
- Python的HttpResponse.write()换行的小问题
- 网络post请求
- 网络get请求
- java操作new HttpPost(URL)和 new URL(shixun_ip) 获取流
- Android实时获取网络信号
- Android开发-网络通信1
- 实验五 — — Java网络编程及安全
- 网络电话是如何实现打到普通话机上的?
- 实验五Java网络编程及安全
- Java实验五报告——TCP传输及加解密
- 实验五 网络编程及安全
- Java实验四 TCP客户端和服务器的应用
- http://www.swoole.com/
- 正确处理浏览器在下载文件时HTTP头的编码问题(Content-Disposition)