Skip to content

Instantly share code, notes, and snippets.

@anuraj
Created March 1, 2022 01:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anuraj/8203eef0cae6259ce54278a10c1978eb to your computer and use it in GitHub Desktop.
Save anuraj/8203eef0cae6259ce54278a10c1978eb to your computer and use it in GitHub Desktop.
CSS Isolation Action Filter for .NET Framework MVC projects
internal class CssInlineMemoryStream : MemoryStream
{
private readonly Stream _stream;
private readonly string _cssFileContent;
public CssInlineMemoryStream(Stream stream, string cssFileContent = "")
{
_stream = stream;
_cssFileContent = cssFileContent;
}
public override void Write(byte[] buffer, int offset, int count)
{
if (!string.IsNullOrEmpty(_cssFileContent))
{
var html = Encoding.UTF8.GetString(buffer);
html = html.Replace("</head>", $"<style>{_cssFileContent}</style></head>");
buffer = Encoding.UTF8.GetBytes(html);
}
_stream.Write(buffer, offset, buffer.Length);
}
}
public class CSSIsolationActionFilterAttribute : ActionFilterAttribute
{
public CSSIsolationActionFilterAttribute()
{
}
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
ViewResult viewResult = filterContext.Result as ViewResult;
RazorView view = viewResult?.View as RazorView;
var viewPath = view?.ViewPath;
var cssFileContents = string.Empty;
if (!string.IsNullOrEmpty(viewPath))
{
var absolutePath = filterContext.HttpContext.Server.MapPath(viewPath);
var cssFile = absolutePath + ".css";
if (File.Exists(cssFile))
{
cssFileContents = File.ReadAllText(cssFile);
}
}
var filter = filterContext.HttpContext.Response.Filter;
filterContext.HttpContext.Response.Filter = new CssInlineMemoryStream(filter, cssFileContents);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment