class MyHandlerFactory:IHttpHandlerFactory
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace WebAppHttpHandlerTest { public class MyHandlerFactory:IHttpHandlerFactory { //IHttpHandlerFactory接口包含两个方法。 //GetHandler返回实现IHttpHandler接口的类的实例, //ReleaseHandler使工厂可以重用现有的处理程序实例。 #region IHttpHandlerFactory 成员 public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated) { string fname = url.Substring(url.LastIndexOf('/') + 1); string cname = fname.Substring(0, fname.IndexOf('.')); string className = "WebAppHttpHandlerTest." + 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 } }
</roleManager> <httpHandlers> <!-- <add verb="*" path="*.sky" type="WebAppHttpHandlerTest.MyFirstHandler, WebAppHttpHandlerTest"/> --> <add verb="*" path="*.sky" type="WebAppHttpHandlerTest.MyHandlerFactory,WebAppHttpHandlerTest"/> </httpHandlers> </system.web> <system.webServer> <modules runAllManagedModulesForAllRequests="true"/> </system.webServer> </configuration>
http://localhost:7088/Handler1.sky
http://localhost:7088/Handler2.sky