19

爲了調試JavaScript & CSS問題,我需要暫時禁用單個請求的綁定和縮小。我想加入一個參數,像這樣的查詢字符串來做到這一點在運行時..如何在運行時臨時禁用捆綁和縮小?

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; 
    } 
} 
  • 是否存在的事實,我對每一個Web請求設置此靜態屬性,任何潛在的問題? (該網絡應用程序將運行在網上農場)
  • 有沒有更好的方法來處理這個問題?
+2

我沒有看到任何錯誤,但我建議使用ActionFilter和pos將緩存開啓/關閉緩存在cookie/session變量中(直到通過調用'DisableOptimizations = false'進行更改)。 –

+0

@BradChristie我喜歡將它存儲在會話中的想法! – jessegavin

回答

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(); 
} 
+0

這真是太棒了。萬分感謝。 – jessegavin

+0

我幾乎完成了基於您的評論編寫我自己的實現,但我更喜歡你的! – jessegavin

+0

真棒 - 謝謝,這真是太棒了 –