Created
March 1, 2022 01:54
-
-
Save anuraj/8203eef0cae6259ce54278a10c1978eb to your computer and use it in GitHub Desktop.
CSS Isolation Action Filter for .NET Framework MVC projects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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