ASP.NET MVC BundleConfig, scripts returning an empty response?

Sam Rueby.NET Tips, Web Development 2 Comments

The Visual Studio template for ASP.NET MVC 5 comes with Microsoft.AspNet.Web.Optimization, which is used in BundleConfig they provide you. I haven’t used this much and wanted to try it. I wiped out the default stuff and included a line for the only script I needed.

public class BundleConfig {
		// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
		public static void RegisterBundles( BundleCollection bundles ) {
			bundles.Add( new ScriptBundle( "~/scripts" ).Include( "~/scripts/MyHappyScript.js" ) );
		}
	}

Looks great, follows the same pattern as their example. And then in your view (probably your _Layout.cshtml) you have:

@Scripts.Render("~/scripts")

Cool. The keys match, it’s one script, there’s no way this can go wrong.

And it doesn’t! If you’re debugging. Works great.

But then if you turn on optimizations, either by setting debug=false in the Web.Config or by specifying BundleTable.EnableOptimizations = true;  manually in the web config, the script isn’t included in the page.

Note to self: always test in release mode before publishing.

What went wrong? I check out the markup:

<script src="/scripts?v=6wfJOVlsRuSqTPF8oc-k_RQlzbkEMu3rrEXGvvc8WyA1"></script>

Okay- looks great. I click on it: totally blank. Nothing. Content length: 0.

Fast forward. It turns out

that if the key you’re using for your bundle, in this case “~/scripts”, matches the virtual path of the file included in the bundle, then it will not be included. To fix this, I changed the key to “~/bundles/scripts” and everything is happy now.