Tuesday, September 4, 2012

Using ASP.NET Bundling and Minification with Web Forms

Bundling and Minification is a new feature of ASP.NET 4.
Learn more from this tutorial http://www.asp.net/mvc/tutorials/mvc-4/bundling-and-minification.

It has been promoted as part of ASP.NET MVC 4, but actually does not depend on MVC stack and may by used within any ASP.NET application including ASP.NET Web Forms.

When you start a new ASP.NET MVC 4 application using Visual Studio template, it sets up all what you need to start using this feature, but if you have an existing ASP.NET application (even not MVC), you have to complete following steps to make it works with your app.


Adding reference to System.Web.Optimization library

System.Web.Optimization is not a part of .NET 4 framework. But it is provisioned by NuGet package manager.

Open NuGet and search for Microsoft.AspNet.Web.Optimization package.



As you may see, it depends on two other packages, but you don't have to worry, NuGet will manage all dependencies and will install them as well.


Now you may see a few new references added to your project:  Antlr3.Runtime, Microsoft.Web.Infrastructure, System.Web.Optimization and WebGrease.


All new referenced are set to be copied to /bin folder (Copy Local = true in property window), so they are deployed to server with your application. No need to mess with GAC :).

Register bundle


All the rest is according to tutorial. Register bundles with Application_Start:

Include bundle in the page

In my scenario I use Web Forms and have an *.aspx with a master page. To include the bundle in the page, it is simply enough to add one line of code within head tag:


Runing application

Now you can run the application. Depending on debug settings in Web.config you will get either all scripts (included in the bundle) included separately in the page (debug="true") for debugging purpose, or single all-in-one minified script include

CSS bundling

In the same manner you can use CSS bundling

Register StyleBundle:


Include in the page: