Request is not available in this context
This is very classic case: If you end up having to check for any data provided by the http instance then consider moving that code under the BeginRequest
event.
void Application_BeginRequest(Object source, EventArgs e)
This is the right place to check for http headers, query string and etc...
Application_Start
is for the settings that apply for the application entire run time, such as routing, filters, logging and so on.
Please, don't apply any workarounds such as static .ctor or switching to the Classic mode unless there's no way to move the code from the Start
to BeginRequest
. that should be doable for the vast majority of your cases.
When you have custom logging logic, it is rather annoying to be forced either not to log application_start or to have to let an exception occurs in the logger (even if handled).
It appears that rather than testing for Request
availability, you can test for Handler
availability: when there is no Request
, it would be strange to still have a request handler. And testing for Handler
does not raise that dreaded Request is not available in this context
exception.
So you may change your code to:
var currContext = HttpContext.Current;
if (currContext != null && currContext.Handler != null)
Beware, in the context of a http module, Handler
may not be defined though Request
and Response
are defined (I have seen that in BeginRequest event). So if you need request/response logging in a custom http module, my answer may not be suitable.
Please see IIS7 Integrated mode: Request is not available in this context exception in Application_Start:
The “Request is not available in this context” exception is one of the more common errors you may receive on when moving ASP.NET applications to Integrated mode on IIS 7.0. This exception happens in your implementation of the Application_Start method in the global.asax file if you attempt to access the HttpContext of the request that started the application.