Less is an excellent tool for any developer to help mange CSS code. SASS is also a great tool that does a similar job but this post is  focused on LESS and bundling it with your ASP.NET MVC web application.

.NET MVC provides a very useful optimisation tool for web sites called bundling. I explain bundling in MVC in a previous post, if you are not familiar with it.

It is possible to neatly integrate LESS with the bundling process, which I will explain and provide examples how to implement.

Firstly you will need to reference the dotless dll into your project, which can be added via Nuget. Create a new class file which I have called LessTransform. This inherits off of IBundleTransform, the interface used to transform CSS or JavaScript files into one file1. Add a method called Process, which will be used to convert the LESS files into CSS.

using System.Web.Optimization;
public class LessTransform : IBundleTransform
    public void Process(BundleContext context, BundleResponse response)
        response.Content = dotless.Core.Less.Parse(response.Content);
        response.ContentType = "text/css";

In the global.asax file add RegisterBundles method with the following code to run the LESS transform and bundle into CSS. The bundle process is better explained in my previous post if you are uncertain on how to implement it.

//Global asax
public void RegisterBundles(BundleCollection bundles)
     var lessBundle = new Bundle("~/Content/BundledLess").Include("~/Content/myDemo.less");
     lessBundle.Transforms.Add(new LessTransform());
     lessBundle.Transforms.Add(new CssMinify());

In between the header reference the bundled LESS into your web application as shown below.


Something I really like about this set-up is you don’t need to rebuild your app every time you make a change to your LESS file. The changes are automatically updated when your refresh your browser. There is no need to run a tool in the background to watch and convert the file into CSS every time it is saved.

Update: After playing around further with intergrating LESS with bundling I have discovered the the paser method fails to import files when using @import. It fails because the file path it tries to find are incorrect and so can’t resolve the file location to import the file. However I have found a bug fix which you just need to copy in with what is created above. View this code that fixes the issue and add to your project.

1. Found useful code on The Official Microsoft ASP.NET Site - Bundling and Minification.