Search code examples
c#asp.netasp.net-mvcbundling-and-minificationasp.net-optimization

Web.Optimizations - any way to get all includes from a Style/Script Bundle?


I'm working with some dynamic bundling which adds CSS and JS files based on configuration.

I spin up a new StyleBundle such that:

var cssBundle = new StyleBundle("~/bundle/css");

Then loop through config and add any found includes:

cssBundle.Include(config.Source);

Following the loop I want to check if there was actually any files/directories included. I know there's EnumerateFiles() but I don't think this 100% serves the purpose.

Anyone else done anything similar previously?


Solution

  • The Bundle class uses an internal items list that is not exposed to the application, and isn't necessarily accessible via reflection (I tried and couldn't get any contents). You can fetch some information about this using the BundleResolver class like so:

    var cssBundle = new StyleBundle("~/bundle/css");
    cssBundle.Include(config.Source);
    
    // if your bundle is already in BundleTable.Bundles list, use that.  Otherwise...
    var collection = new BundleCollection();
    collection.Add(cssBundle)
    
    // get bundle contents
    var resolver = new BundleResolver(collection);
    List<string> cont = resolver.GetBundleContents("~/bundle/css").ToList();
    

    If you just need a count then:

    int count = resolver.GetBundleContents("~/bundle/css").Count();
    

    Edit: using reflection

    Apparently I did something wrong with my reflection test before.

    This actually works:

    using System.Reflection;
    using System.Web.Optimization;
    
    ...
    
    int count = ((ItemRegistry)typeof(Bundle).GetProperty("Items", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(cssBundle, null)).Count;
    

    You should probably add some safety checks there of course, and like a lot of reflection examples this violates the intended safety of the Items property, but it does work.