Implementing CSS from MVC Controller

Sometimes your CSS needs to come from a database.  Ever wonder how to minify that return value.  This article is about returning dynamic CSS from an MVC controller and minifying it on the way out.

<p>Implementing CSS from MVC Controller</p>

Step 1: Create a controller action that accesses the database

    public ContentResult SiteCss()
            string css = this.SiteSettings.MainCss;
            if (css == null)
                css = "";
            if (css != "")
                css = Helpers.HtmlExtensions.RemoveWhiteSpaceFromStylesheets(css);
            return Content(css, "text/css");

Step 2: Implement the controller in HTML

   <link href="@Html.ResolveServerUrl("~/Home/SiteCss", true)" rel="stylesheet" type="text/css" />

Step 3: Cleanup the data in the CSS from the database

public static string RemoveWhiteSpaceFromStylesheets(string body)
            body = Regex.Replace(body, @"[a-zA-Z]+#", "#");
            body = Regex.Replace(body, @"[\n\r]+\s*", string.Empty);
            body = Regex.Replace(body, @"\s+", " ");
            body = Regex.Replace(body, @"\s?([:,;{}])\s?", "$1");
            body = body.Replace(";}", "}");
            body = Regex.Replace(body, @"([\s:]0)(px|pt|%|em)", "$1");

            // Remove comments from CSS
            body = Regex.Replace(body, @"/\*[\d\D]*?\*/", string.Empty);

            return body;

*This code came from

Once these three steps are complete, test it out.  In google chrome press ctrl+J to get the developer tools, you should now be able to go under the network tab, click on CSS, choose your controller URL and Bada Bing, it is much smaller.  This is how I have implemented the feature, it puts more load on the server to minify in every step, but allows you full control of when it is minifyed and when it is not.

Last Updated: 3/20/2017 5:51:41 PM