Asp.Net HttpContext.RemapHandler 用法

最近在看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页面



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值