How can I include SRI hash in ScriptBundle for .NET MVC (4.7.2) application?

920 views Asked by At

Currently my bundles are using local copies of common libraries.

bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                      "~/Scripts/bootstrap.js",
                      "~/Scripts/moment.min.js",
                      "~/Scripts/bootstrap-datetimepicker.min.js",
                      "~/Scripts/respond.js"));

I want to convert to using CDNs, and want to make sure I am adhearing to SRI by including the hash value. I've found plenty of articles for using a CDN in bundle config but nothing about how to include SRI hash, and the crossorigin tag when bundling.

Please assist me.

2

There are 2 answers

1
Jayrag Pareek On

try this:

 public static void RegisterBundles(BundleCollection bundles)
 {
    BundleTable.EnableOptimizations = true;
    string version = string.Format("{0}", DateTime.Now.ToString("yyyyMMddHHmmss"));
    bundles.UseCdn = true;
    var cdnUrl = "CDN url"+ "{0}?" + version;
    
    bundles.Add(new ScriptBundle("~/bundles/bootstrap", string.Format(cdnUrl, "bundles/bootstrap")).Include(
                      "~/Scripts/bootstrap.js",
                      "~/Scripts/moment.min.js",
                      "~/Scripts/bootstrap-datetimepicker.min.js",
                      "~/Scripts/respond.js"));
 
 }

and add this line in Global.asax.cs inside Application_BeginRequest for allow crossorigin

HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "CDN url");
1
Anurag Tidke On

Try below code :

bundles.UseCdn = true; bundles.Add(new ScriptBundle("~/bundles/jquery", "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js").Include( "~/Scripts/jquery-{version}.js"));

And Run your application in debug="false" mode or use BundleTable.EnableOptimizations = true;