你不知道的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中,我们可 以根据具体业务选择不同的工厂模式实现方式,下面的代码中包括了通过判断后缀实现的简单工厂模式和通过反射实现的工厂模式两种实现方式。

四、求关注、求推荐
兄台给点鼓励吧 O(∩_∩)O~,你的鼓励是我继续写好这一系列的理由
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?