自定义IHttpHandlerFactory中的HttpContext.Current为null

时间:2013-08-26 19:46:11

标签: asp.net httphandlerfactory

public class HandlerFactory : IHttpHandlerFactory
{
    public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
    {
        // lots of code
    }

    public void ReleaseHandler(IHttpHandler handler)
    {
        // HttpContext.Current is always null here.
    }
}

如何使HttpContext.Current可用(或使用替代方法存储每个请求变量,以便可以在ReleaseHandler中检索它们)?

1 个答案:

答案 0 :(得分:0)

在.NET Reflector中查看System.Web程序集后,似乎可以在请求的生命周期之外调用ReleaseHandler,这意味着使用HttpContext.Current的概念不适用。但是,我可以提出一些建议:

  1. 如果您控制GetHandler返回的处理程序的实现,您可以向其添加公共或内部成员,以表示您希望在ReleaseHandler中使用的特定数据。

    public class MyHandler : IHttpHandler
    {
        /* Normal IHttpHandler implementation */
    
        public string ThingIWantToUseLater { get;set; }
    }
    

    然后在你的处理程序工厂中:

    public class HandlerFactory : IHttpHandlerFactory
    {
        public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
        {
            // lots of code
            return new MyHandler()
            {
                    ThingIWantToUseLater = "some value"
            };
        }
    
        public void ReleaseHandler(IHttpHandler handler)
        {
             if (handler is MyHandler)
             {
                  var myHandler = handler as MyHandler;
                  // do things with myHandler.ThingIWantToUseLater
             }
        }
    }
    
  2. 可以使用上面的方法,只是在处理程序的实现中滑动实际的HttpContext。我认为这可能导致奇怪的建筑场所,但这是你的呼唤。