If you have some code that you want to run locally for testing, you can check current "Request" and look at methods like "Request.IsLocal" to conditionally include test modules. However, there are times you need to bypass the ASP.NET application life cycle and directly exclude or include a source code from compiling using compilation directives.
Here is an example of a use case where you might need to bypass the application life cycle in order to run code during development. Consider a case where you need to include some JS and CSS styles, say, you have QUnit files stashed somewhere in a folder of your app, during development.
If you are working on an ASP.NET page, view or controller you can access incoming HTTP Request by using:
Here is an example of a use case where you might need to bypass the application life cycle in order to run code during development. Consider a case where you need to include some JS and CSS styles, say, you have QUnit files stashed somewhere in a folder of your app, during development.
If you are working on an ASP.NET page, view or controller you can access incoming HTTP Request by using:
var currentRequest = Request;
or if you are accessing the "Request" object from a class that does not inherit from "Page" in ASP.NET or "ViewPage" in MVC (or any other object that has the current HTTP context) using:
var currentRequest = System.Web.HttpContext.Current.Request;
The Problem: If you add "Request" or "System.Web.HttpContext.Current.Request" in your "BundleConfig" file, your application will throw an error. The error is prompted because the "Request" object is not yet available in the application life cycle.
Bundling runs in Application_Start routine (well before the "Request" object is instantiated)
Page life cycle for an ASP.NET request
Page life cycle for an ASP.MVC request
Here is an example directive that checks to see if you are running your application in "DEBUG" mode.
#if DEBUG //Include testing bundles #else //Exclude testing bundles #endif
Compilation directives work outside the scope of the HTTP Context as a result your code will run without any issues. You can find more information about compilation directives on MSDN site.
Comments