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.
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.
You could use the Conditional attribute and put it on a method in your base controller. Something like this:
public class BaseController : Controller {
public BaseController() {
SetupDebugData();
}
[Conditional("DEBUG")]
public void SetupDebugData() {
Session["User"] = "1";
}
}
The call to SetupDebugData will be optimized away for Release builds. Then you just inherit from this controller in your other controllers:
public class AdminController : BaseController {
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With