1

I'm working with .Net MVC bundling and minification. It does the job just fine, except you end up with a url like the following:

/bundles/AllMyScripts?v=r0sLDicvP58AIXN_mc3QdyVvVj5euZNzdsa2N1PKvb81

The project will have static files sitting in AWS Cloudfront, and by default it doesn't like querystrings. It can be changed to support this, but there is a performance penalty.

Can bundling be configured to put the token in the filename instead of the querystring? I'm also open to using something other than Web Grease.

3
  • I may be off, but I am not sure what one has to do with the other? MVC bundling will gather the files to be bundled, bundle them and return them from the web server and not from the actual CDN. And as far as I know, you can't store the bundles outside of your web app (if you can, that would be awesome and please correct me). If you are wanting your compressed files to sit outside of your web app, I think you will need to manually compress your items.
    – Tommy
    May 10, 2013 at 14:44
  • @Tommy The CDN pulls from the source if it doesn't have it in cache. A request cdn.mysite.com/content/css/min.css would go to the CDN, and it it wasn't there, the CDN would request this from the source - which is where .net comes into play. You don't push to a CDN, it pulls from you.
    – ScottE
    May 10, 2013 at 14:53
  • Oh, I see what you are asking now, I was looking at your problem in the opposite file flow direction. My mistake. I thought you were asking about the actual pull for the bundling process and not the CDN distributing the bundles.
    – Tommy
    May 10, 2013 at 14:56

3 Answers 3

1

Ok, I've come up with a decent solution involving url rewriting and a custom html helper.

web.config:

  <rule name="BundlingRewrite" stopProcessing="true">
      <match url="^content/min/([^/]+)/([^/]+)/?$" />
      <conditions>
          <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
          <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
      </conditions>
      <action type="Rewrite" url="content/min/{R:1}?v={R:2}" />
  </rule>

helper:

public static IHtmlString RenderCdnCss(this HtmlHelper helper, params string[] paths)
{
    if (BundleTable.EnableOptimizations)
    {
        StringBuilder sb = new StringBuilder();
        Uri baseUri = helper.ViewContext.HttpContext.Request.Url;

        foreach (string s in paths) {
            Uri uri = new Uri(baseUri, BundleTable.Bundles.ResolveBundleUrl(s));
            sb.AppendFormat("<link href=\"{0}\" rel=\"stylesheet\"/>", uri.PathAndQuery.Replace("?v=", "/"));                    
        }
        return new HtmlString(sb.ToString());
    }
    return Styles.Render(paths);
}

The helper translates the bundled url into something more CDN friendly. For example:

/content/min/css?v=3GWBEyScjC610oPQm0JVybboQ_EmX3StAuCZjd_B7bE1

becomes

/content/min/css/3GWBEyScjC610oPQm0JVybboQ_EmX3StAuCZjd_B7bE1

The url rewrite (IIS Url Rewrite 2.0) looks for a url inside content/min/{some folder}/{some token} and rewrites it to content/min/{some folder}?v={some token} (what the path looks by default)

So, the bundler is none the wiser, and the path becomes CDN friendly. In my case I will also prepend the cdn url to the front of the url, but that's not included above.

0
+100

You can use a MapRoute and a Controller to rewrite the bundle URL to be CDN friendly.

Instead of /bundles/AllMyScripts?v=r0sLDicvP58AIXN_mc3QdyVvVj5euZNzdsa2N1PKvb81 you will have CDN_Bundle/bundles/AllMyScripts/r0sLDicvP58AIXN_mc3QdyVvVj5euZNzdsa2N1PKvb81.

RouteMap:

    routes.MapRoute(
            name: "CDN_Bundle",
            url: "CDN_Bundle/{*virtualPath}",
            defaults: new { controller = "CDN_Bundle", action = "Index" }

Action:

    public ActionResult Index(string virtualPath)
    {
        virtualPath = virtualPath.Trim('/');
        int lastSlash = virtualPath.LastIndexOf("/");
        string hashCode = virtualPath.Substring(lastSlash + 1, virtualPath.Length - lastSlash -1 );
        virtualPath = virtualPath.Substring(0, virtualPath.LastIndexOf("/"));

        WebClient webClient = new WebClient();
        webClient.Headers.Add("user-agent", Request.UserAgent);
        Stream data = webClient.OpenRead(Request.Url.GetLeftPart(UriPartial.Authority) + Path.Combine(Request.ApplicationPath, virtualPath) + "?v=" + hashCode);
        StreamReader reader = new StreamReader(data);
        string content = reader.ReadToEnd();

        return Content(content);
    }

and use this instead of Scripts.Render

         <script src="/cdn_bundle@(System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/bundles/AllMyScripts").Replace("?v=","/"))"></script>
5
  • It's a fine idea, but there must be a more efficient way of doing this!
    – ScottE
    May 15, 2013 at 1:28
  • @ScottE The effective way is minifying the scripts manually by WG and put them on the AWS CloudFront, then bundle them and set UseCdn property of the bundle to true. See Amazon CloudFront, See Using a CDN in Bundling and Minification May 15, 2013 at 5:28
  • I like that suggestion better. Could you explain that suggestion in more detail?
    – ScottE
    May 15, 2013 at 11:06
  • @ScottE There are two link in my previous comment about using `UseCdn' property and how to add static file to Amazon CloudFront.But I cannot understand why you think my approach is not effective. As mentioned in your comment CDN only request the object if it hadn't it in their cache. Therefore the action is called once and there is no performance issue here. May 15, 2013 at 18:05
  • Thanks for the suggestion @Kambiz, but I went a bit of a different direction. I did use System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl, however. Also, that's a fair point about the CDN - once cached the routine won't get hit until it's changed / stale.
    – ScottE
    May 15, 2013 at 19:01
0

Not sure if i've picked up what your after correctly but..

When you define bundles in BundelConfig there is a parameter of ScriptBundle called CdnPath that can be set for each bundel to a CDN location.

In RegisterBundles

Dim bundel As New ScriptBundle("~/bundles/myfoo")
bundel.CdnPath = "http://foo.com/foo.js"

bundles.UseCdn = True

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.