IHttpHandler
工厂
ASP.NET Framework实际不直接将相关的页面资源HTTP请求定位到一个其内部默认的IHttpHandler容器之上,而定位到了其内部默认的IHttpHandler工厂上。IHttpHandler工厂的作用是对IHttpHandler容器进行调度和管理。
IHttpHandlerFactory接口包含两个方法。GetHandler返回实现IHttpHandler接口的类的实例,ReleaseHandler使工厂可以重用现有的处理程序实例。
示例2:
using
System;
using
System.Collections.Generic;
using
System.Text;
using
System.Web;
namespace
MyHandler
{
public class MyHandlerFactory : IHttpHandlerFactory
{
#region
IHttpHandlerFactory
成员
public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
{
string fname = url.Substring(url.IndexOf('/') + 1);
while (fname.IndexOf('/') != -1)
fname = fname.Substring(fname.IndexOf('/') + 1);
string cname = fname.Substring(0, fname.IndexOf('.'));
string className = "MyHandler." + cname;
object h = null;
try
{
//
采用动态反射机制创建相应的IHttpHandler实现类。
h = Activator.CreateInstance(Type.GetType(className));
}
catch (Exception e)
{
throw new HttpException("
工厂不能为类型"
+cname+"
创建实例。"
,e);
}
return (IHttpHandler)h;
}
public void ReleaseHandler(IHttpHandler handler)
{
}
#endregion
}
public class Handler1 : IHttpHandler
{
#region
IHttpHandler
成员
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
context.Response.Write("<html><body><h1>
来自Handler1的信息。</h1></body></html>"
);
}
#endregion
}
public class Handler2 : IHttpHandler
{
#region
IHttpHandler
成员
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
context.Response.Write("<html><body><h1>
来自Handler2的信息。</h1></body></html>"
);
}
#endregion
}
}