ASP.NET MVC Debug-mode settings
asp.net-mvc, c#, debugging, razor
Solution
The reason that this throws an error is because the Session object is associated with a request. There is no request in the `Application_Start` event. You could move this logic to the `Application_AcquireRequestState` event handler and it would work fine.
protected void Application_AcquireRequestState(object sender, EventArgs e)
{
if (HttpContext.Current.IsDebuggingEnabled)
{
HttpContext.Current.Session["user"] = "1";
}
else
{
HttpContext.Current.Session["user"] = "0";
}
}
EDIT
After further research, I was mistaken. In the .NET pipeline, the above event handler is the first place that you can access the session object. It has not been retrieved from the server in the `Application_BeginRequest` which is why you are getting a `NullReferenceException` still. I tested the above code in MVC 5 and had no issues.
Also, instead of having to rely on compiler constants, you can easily tell if you are in debug mode or not using the above syntax of `HttpContext.Current.IsDebuggingEnabled`. This basically is a wrapper for checking the web.config attribute on the `compilation` tag and seeing if `debug="true"`
Note - You have to use the fully qualified name of HttpContext.Current.Session (as above) since the global event handlers do not have a direct inheritance of the current HttpContext.
Problem
Is there a way to setup some default settings for webpages being ran on debug mode? For example, I'd like to set a default session userid on debug mode, but trying this in Application_Start() causes errors: ``` protected void Application_Start() { #if DEBUG Session["User"] = "1" #endif } ``` I could instead choose to place that in controllers, but that'd require a lot of code duplication.