Using MVC bundling to generate custom CSS from LESS files

269 Views Asked by At

I have a multiclient system whereby different clients have different brand colours.

These colours are stored in the DB and referenced throughout my LESS files as @color{1-3}.

We used to maintain a colors.less file with a reference to all places where these colours featured. In a client-neutral situation we would just render the normal bundle with our brand colours but within a client area we would inject a stored CSS file generated when the client colours changed in the DB.

This worked fine but maintaining the colours.less file was becoming a bit unwieldy so what I'd like to do is render the css "real time" so that no css file needs to be generated manually. Obviously I can't do this every request because it would hammer the server with a fairly intensive css generation every page load.

My question is how can i use bundling or some other form of caching to generate this css on the fly (i.e without actually storing the css files) without hammering the server?

1

There are 1 best solutions below

0
On

you can implement a custom http handler:

public class CustomHandler : IHttpHandler
{
    #region IHttpHandler Members

    public bool IsReusable
    {
        // Return false in case your Managed Handler cannot be reused for another request.
        // Usually this would be false in case you have some state information preserved per request.
        get { return true; }
    }

    public void ProcessRequest(HttpContext context)
    {
        var sb = new StringBuilder();
        // read values from db and cache them with HttpContext.Current.Cache
        sb.Append(".black : { color: 'black'; }");

        context.Response.Clear();
        context.Response.ContentType = "text/css";
        context.Response.Write(sb.ToString());
    }

    #endregion
}

web.config:

 <system.webServer>    
    <handlers>
      <add name="ColorsHandler" verb="GET" path="colors.axd" type="WebApplication3.Infrastructure.CustomHandler, WebApplication3, Version=1.0.0.0, Culture=neutral" />
    </handlers>
  </system.webServer>

the only limitation is that you cannot reference this handler as MVC Bundle because MVC bundle can handle only static files. Thus you have to reference it as stylesheet:

 <link rel="stylesheet" href="~/colors.axd" type="text/css">