HttpContext.Current is null in custom IHttpHandlerFactory

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.
    }
}

How can I make HttpContext.Current available (or use alternative approach to store per-request variables such that they can be retrieved in ReleaseHandler)?

Answers


After looking at the System.Web assembly in .NET Reflector, it appears that ReleaseHandler may be called outside of the lifecycle of a request, which means that the concept of having HttpContext.Current is not applicable. However, there are a couple of things I could suggest:

  1. If you control the implementation of the handler that GetHandler returns, you could add public or internal members to it to represent the specific data you are looking to use in ReleaseHandler.

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

    Then in your handler factory:

    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. Could use the above approach and just slip the actual HttpContext in your implementation of the handler. I think that could lead to weird architectural places, but it's your call.


Need Your Help

Error while installing Sinch JS RTC as npm package

node.js sinch

I need to use Sinch IM feature from my backend server and I am trying to install sinch-rtc as node.js package. I get the following error when I use the command : npm install sinch-rtc --save

What does super's clone do?

java

I am reading about clone from Effective Java