How to merge CSS files in ASP.NET

ASP.NET provides ScriptManager using which we can combine our script files.
There is already a tip which describes “How to merge your Javascript files in ASP.NET”.

But ScriptManager in ASP.NET does not provide us the facility to merge CSS files. We can achieve it by the following steps: Step 1: Create an HTTP handler which will combine CSS files. Step 2: Use that HTTPHandler instead of linking to any external CSS files. Step 1: [Create an HTTP handler] For creating an HTTP handler, we have to create a class which will in inherit IHttpHandler interface.

The code below is an HTTP handler, to which we will pass name of the CSS files and it will give the combined css file.

It takes the name (fully qualified name) of the CSS files (names separated by comma) and reads each CSS file and give the response back, which contains the combined version of the CSS files.

public class ResourceCombiner : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        // Get the list of CSS files from QueryString.
        string files = context.Request.QueryString["fileName"];
        if (string.IsNullOrEmpty(files))
        {
            return; // If no file name is mentioned then don't proceed.
        }
 
        // Get the list of files specified in the querystring (joined by ',').
        string[] arrFileNames = files.Split(',');
        if ((arrFileNames != null) && (arrFileNames.Length > 0))
        {
            string filePath = string.Empty;
 
            // Read the content of each CSS file and write it in the response.
            for (int fileCount = 0; fileCount < arrFileNames.Length; fileCount++)
            {
                filePath = context.Server.MapPath(arrFileNames[fileCount]).Trim();
                if (File.Exists(filePath)) // Check if the file exists in the physical location or not.
                {
                    context.Response.Write(File.ReadAllText(filePath));
                }
            }
            context.Response.ContentType = "text/css"; // Set the content type.
        }
    }
}

The below 3 lines are placed in the web.config file to access the HTTP handler.

    

Step 2: [Use HTTPHandler to merge the CSS files] Now the next step is to use the HTTP handler.

Suppose in any of your page you are using some external stylesheets files, so include those CSS files to your web page you will write the following lines.

 

But since we will be using the HTTP handler for combining the CSS files, we will write something like:

So the above line will invoke the HTTP handler which has the merging logic.
In the handler, we have only the merging logic, if we want we can also add caching logic, i.e after merging the files it will cache and the browser does not have to download the file again and again.

Hope this helps you : )

150 150 Burnignorance | Where Minds Meet And Sparks Fly!