你不知道的HttpHandler相关知识

一、关于IHttpHandler.IsReusable

  很多人不明白,这哥们到底干嘛的,估计是微软最初的一个想法--让一个对象可以一直不断地被重复使用

,但这个想法不成熟,会带来很多隐藏问题,一个对象作为始终存在的对象,只要被污染了,它就不能正常使用了.

所以,我们会看见微软自己也一直让这个属性值为false;

二、关于ashx的Handler执行方式

  扩展名为ashx的请求是通过SimpleHandlerFactory处理程序工厂完成的,当请求一个ashx扩展名的服务器上资源 时,SimpleHandlerFactory将找到对应的ashx文件,通过这个文件找到对应的处理程序。最 后,SimpleHandlerFactory通过反射创建一个此类型处理程序对象实例

复制代码
using System;
using System.Runtime;
using System.Web.Compilation;
namespace System.Web.UI
{
    internal class SimpleHandlerFactory : IHttpHandlerFactory2, IHttpHandlerFactory
    {
        [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
        internal SimpleHandlerFactory()
        {
        }
        public virtual IHttpHandler GetHandler(HttpContext context, string requestType, string virtualPath, string path)
        {
            return ((IHttpHandlerFactory2)this).GetHandler(context, requestType, VirtualPath.CreateNonRelative(virtualPath), path);
        }
        IHttpHandler IHttpHandlerFactory2.GetHandler(HttpContext context, string requestType, VirtualPath virtualPath, string physicalPath)
        {
            BuildResultCompiledType buildResultCompiledType = (BuildResultCompiledType)BuildManager.GetVPathBuildResult(context, virtualPath);
            Util.CheckAssignableType(typeof(IHttpHandler), buildResultCompiledType.ResultType);
            return (IHttpHandler)buildResultCompiledType.CreateInstance();
        }
        public virtual void ReleaseHandler(IHttpHandler handler)
        {
        }
    }
}
复制代码

三、HttpHandlerFactory到底是何物?

  从上面的ashx可以得知,ASP.NET实际不会将指定格式的HTTP请求直接定位到具体的IHttpHandler容器之上,而定位到了其内部默认的IHttpHandlerFactory上。

IHttpHandlerFactory的作用是对IHttpHandler容器进行调度和管理。

  如果我们自定义的HttpHandler比较多,会在Web.config中注册很多HttpHandler类,这时把这些HttpHandler通过一个HttpHandlerFactory来集中管理就显的非常必要,

此时只需要在Web.config中注册此HttphandlerFactory即可。

  IHttpHandlerFactory接口包含两个方法。GetHandler返回实现IHttpHandler接口的类的实例,ReleaseHandler使工厂可以重用现有的处理程序实例。

实现一个自定义的HttphandlerFactory同样需要两步:

  第一:定义一个实现了IHttpHandlerFactory接口的类,并实现其GetHandler方法。在GetHandler中,我们可 以根据具体业务选择不同的工厂模式实现方式,下面的代码中包括了通过判断后缀实现的简单工厂模式和通过反射实现的工厂模式两种实现方式。

  

View Code

 

四、求关注、求推荐

        兄台给点鼓励吧 O(∩_∩)O~,你的鼓励是我继续写好这一系列的理由

 
posted @ 2015-02-12 16:04  迅捷网络[来送福利]  阅读(583)  评论(1编辑  收藏  举报