IHttpHandlerFactory 概述
上下文知识请参见:《Http Handler 介绍》
IHttpHandlerFactory 概述
现在假设我们有这样的需求,我们不仅想要处理 .rss 后缀名,还想要能够处理 .atom后缀名,假设处理atom的类命名为AtomHandler,那么我们的Web.config该如何设置呢?我想应该是这样的:
<httpHandlers>
<add path="*.rss" type="RssFeadsLib.RSSHandler" verb="GET" />
<add path="*.atom" type="RssFeadsLib.AtomHandler" verb="GET" />
</httpHandlers>
如果我们有很多个HttpHandler分别映射不同后缀名的请求,这样我们的Web.config会变得很冗长,或者,我们只有在程序运行时才能确切地知道使用哪个Handler,这个时候,可以考虑实现 IHttpHandlerFactory来完成这一过程。
IHttpHandlerFactory的定义是这样的:
public interface IHttpHandlerFactory{
    IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated);
    void ReleaseHandler(IHttpHandler handler);
}
可见,需要实现两个方法,分别是 GetHandler() 和 ReleaseHandler()。
- GetHandler(),返回实现了IHttpHandler接口的类的实例。
- ReleaseHandler(),使得Factory可以重复使用一个已经存在的Handler实例。
对于上面 .atom 和 .rss 的问题,我们可以这样来实现 IHttpHandlerFactory接口:
class HandlerFactory:IHttpHandlerFactory{
    public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated){
       string path = context.Request.PhysicalPath;
       if (Path.GetExtension(path) == ".rss"){
           return new RSSHandler();
       }
       if (Path.GetExtension(path) == ".atom"){
           return new ATOMHandler();
       }
       return null;
    }
    public void ReleaseHandler(IHttpHandler handler){
    }
}
这时,在Web.Config 中<system.web>节点下进行如下设置即可:
<httpHandlers>
<add path="*.rss,*.atom" type=" RssFeadsLib.HandlerFactory" verb="GET" />
</httpHandlers>
但是,这不能简化IIS中ISAPI的设置,还是需要手动去对.rss和.atom分别设置。
This posting is provided "AS IS" with no warranties, and confers no rights.
 
                    
                     
                    
                 
                    
                 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号 
