title: Workaround for HttpContext.HideRequestResponse being internal? Detect if HttpContext.Request is really available?
body: <p>We're migrating an application to use IIS7 integrated mode.  In library code that is designed to work either within the context of an HTTP request or not, we commonly have code like this:</p>
  
  <pre><code>if (HttpContext.Current != null &amp;&amp;
      HttpContext.Current.Request != null) {
  
      // do something with HttpContext.Current.Request
  
  } else {
  
      // do equivalent thing without HttpContext..
  
  }
  </code></pre>
  
  <p>But in IIS7 integrated mode the check for <code>HttpContext.Current.Request</code> throws an exception whenever this code is called from <code>Application_Start</code>.</p>
  
  <pre><code>protected void Application_Start(object sender, EventArgs e)
  {
      SomeLibrary.DoSomethingWithHttpContextCurrentDetection();
  }
  </code></pre>
  
  <p>Results in:</p>
  
  <blockquote>
    <p>System.Web.HttpException: Request is not available in this context</p>
  </blockquote>
  
  <p>How can I detect whether the request is really available <strong>without wrapping these calls in an exception handler</strong> and taking action based on whether an exception is generated or not.  </p>
  
  <p>Looking at <code>HttpContext</code> in Reflector I see it has an <code>internal bool HideRequestResponse</code> field but it's internal so I can only get to it with reflection and that's fragile.  Is there a more official/approved way to determine if it's ok to call <code>HttpContext.Request</code>?</p>
  
  <p>This blog post about the subject says not to use <code>HttpContext</code>, but how, in generic library code, can you determine if it's ok to use <code>HttpContext</code>?</p>
  
  <p><a href="http://mvolo.com/iis7-integrated-mode-request-is-not-available-in-this-context-exception-in-applicationstart/" rel="noreferrer">http://mvolo.com/iis7-integrated-mode-request-is-not-available-in-this-context-exception-in-applicationstart/</a></p>
  
  <p>I'm using the work-around mentioned there which is to use <code>Application_BeginRequest</code> and an <code>initialized</code> field to only initialize once as part of <code>BeginRequest</code>, but that has to be done in every calling application whereas I'd prefer to make the library code more robust and handle this situation regardless of where it's called from.</p>