How to force BundleCollection to flush cached script bundles in MVC4

前端 未结 6 1372
梦谈多话
梦谈多话 2020-11-29 19:28

... or how I learned to stop worrying and just write code against completely undocumented APIs from Microsoft. Is there any actual documentation of the official

6条回答
  •  广开言路
    2020-11-29 19:55

    Bearing in mind Hao Kung's recommendations to not do this because of web farm scenarios, I think there are a lot of scenarios where you might want to do this. Here is a solution:

    BundleTable.Bundles.ResetAll(); //or something more specific if neccesary
    var bundle = new Bundle("~/bundles/your-bundle-virtual-path");
    //add your includes here or load them in from a config file
    
    //this is where the magic happens
    var context = new BundleContext(new HttpContextWrapper(HttpContext.Current), BundleTable.Bundles, bundle.Path);
    bundle.UpdateCache(context, bundle.GenerateBundleResponse(context));
    
    BundleTable.Bundles.Add(bundle);
    

    You can call the above code at any time and your bundles will get updated. This works both when EnableOptimizations is true or false - in other words, this will throw out the correct markup in debug or live scenarios, with:

    @Scripts.Render("~/bundles/your-bundle-virtual-path")
    

提交回复
热议问题