我需要能够暂时禁用单个请求的捆绑和缩小,以便调试JavaScript& CSS问题。我想在运行时通过向QueryString添加一个参数来实现这一点,如此...
http://domain.com/page?DisableOptimizations=true
这是我正在考虑的方法。
protected void Application_BeginRequest(object sender, EventArgs e)
{
// Enable for every request
BundleTable.EnableOptimizations = true;
// Disable for requests that explicitly request it
bool disable;
bool.TryParse(Context.Request.QueryString["DisableOptimizations"], out disable);
if (disable)
{
BundleTable.EnableOptimizations = false;
}
}
答案 0 :(得分:9)
扩展我在评论中提到的内容:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class OptimizationsDebuggingAttribute : ActionFilterAttribute
{
private const String PARAM_NAME = "DisableOptimizations";
private const String COOKIE_NAME = "MySite.DisableOptimizations";
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
Boolean parsedPref;
Boolean optimizationsDisabled = false;
if (filterContext.HttpContext.Request.QueryString[PARAM_NAME] != null)
{ // incoming change request
var pref = filterContext.HttpContext.Request.QueryString[PARAM_NAME].ToString();
if (Boolean.TryParse(pref, out parsedPref))
{
optimizationsDisabled = parsedPref;
}
}
else
{ // use existing settings
var cookie = filterContext.HttpContext.Request.Cookies[COOKIE_NAME];
if (cookie != null && Boolean.TryParse(cookie.Value, out parsedPref))
{
optimizationsDisabled = parsedPref;
}
}
// make the change
System.Web.Optimization.BundleTable.EnableOptimizations = !optimizationsDisabled;
// save for future requests
HttpCookie savedPref = new HttpCookie(COOKIE_NAME, optimizationsDisabled.ToString())
{
Expires = DateTime.Now.AddDays(1)
};
filterContext.HttpContext.Response.SetCookie(savedPref);
base.OnActionExecuting(filterContext);
}
}
然后当然实现它看起来像:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new OptimizationsDebuggingAttribute());
}
或者,如果您更喜欢实践方法:
[OptimizationsDebugging]
public ActionResult TroublesomeAction()
{
return View();
}