Created
October 9, 2014 12:35
-
-
Save aolde/9075182ce3ceed91e2b5 to your computer and use it in GitHub Desktop.
Turn off ASP.NET Bundling based on "debug" query string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] | |
public class DebugBundlingAttribute : ActionFilterAttribute | |
{ | |
private const string DEBUG_MODE_SESSION_KEY = "BundlingDebugMode"; | |
public bool PersistPerSession { get; set; } | |
public DebugBundlingAttribute() | |
{ | |
PersistPerSession = true; | |
} | |
public override void OnActionExecuting(ActionExecutingContext filterContext) | |
{ | |
var session = filterContext.HttpContext.Session; | |
var debugQueryString = filterContext.HttpContext.Request.QueryString["debug"]; | |
if (debugQueryString != null) | |
{ | |
bool isUserRequestingDebug; | |
bool.TryParse(debugQueryString, out isUserRequestingDebug); | |
SetOptimizationEnabled(!isUserRequestingDebug); | |
if (PersistPerSession && session != null) | |
{ | |
session[DEBUG_MODE_SESSION_KEY] = isUserRequestingDebug; | |
} | |
} | |
else | |
{ | |
// user didn't supply a debug querystring but might have persisted a setting in sessions. | |
if (PersistPerSession && session != null) | |
{ | |
var sessionValue = session[DEBUG_MODE_SESSION_KEY]; | |
if (sessionValue != null) | |
{ | |
SetOptimizationEnabled(!(bool)sessionValue); | |
} | |
} | |
} | |
} | |
private static void SetOptimizationEnabled(bool value) | |
{ | |
var instance = ManagerProperty.GetValue(null, null); | |
OptimizationEnabledProperty.SetValue(instance, value); | |
} | |
private static readonly PropertyInfo ManagerProperty = typeof(Scripts) | |
.GetProperty("Manager", BindingFlags.Static | BindingFlags.NonPublic); | |
private static readonly PropertyInfo OptimizationEnabledProperty = Assembly | |
.GetAssembly(typeof(Scripts)) | |
.GetType("System.Web.Optimization.AssetManager") | |
.GetProperty("OptimizationEnabled", BindingFlags.Instance | BindingFlags.NonPublic); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class FilterConfig | |
{ | |
public static void RegisterGlobalFilters(GlobalFilterCollection filters) | |
{ | |
filters.Add(new DebugBundlingAttribute()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment