Output .NET MVC bundle content as a string with Razor

Sometimes you might run into situations when you need to output the contents of your style or script bundle as a raw string inline. For example if you need to pass your markup and stylesheets to somewhere else without having any external resources in it, this would be a handy solution.

Yesterday I had to do some optimizations for our project’s HTML-to-PDF rendering (EVO PDF). One of the optimizations was to reduce number of requests on the page. I generated an inline CSS string from my LESS bundle and base64 encoded images on my page so that I ended up with only one request and speeding up the rendering by half.

Here’s a simple trick for outputting .NET MVC bundle contents as a string with Razor:

.cshtml

@{}
<!DOCTYPE html>  
<html>  
    <head>
        <meta charset="utf-8" />
        <style type="text/css">
            @Html.Raw(BundleTable.Bundles.GetBundleFor("~/VIRTUAL_PATH_TO_YOUR_BUNDLE").GenerateBundleResponse(new BundleContext(this.Context, BundleTable.Bundles, string.Empty)).Content)
        </style>
    </head>
    ...
</html>