Skip to content

Instantly share code, notes, and snippets.

@SebastianStehle
Last active August 7, 2017 18:48
Show Gist options
  • Save SebastianStehle/768e09a041be3b255a171f975209abe2 to your computer and use it in GitHub Desktop.
Save SebastianStehle/768e09a041be3b255a171f975209abe2 to your computer and use it in GitHub Desktop.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class MinifyHtmlAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
if (IsSupportedContentType(filterContext))
{
filterContext.HttpContext.Response.Filter = new MinifyHtmlStream(filterContext.HttpContext.Response.Filter);
}
}
private static bool IsSupportedContentType(ControllerContext filterContext)
{
return filterContext.HttpContext.Response.Filter != null && filterContext.HttpContext.Response.ContentType.Equals("text/html", StringComparison.OrdinalIgnoreCase);
}
}
public sealed class MinifyHtmlStream : MemoryStream
{
private static readonly Regex RegExpressionWhiteSpaces = new Regex(@"(?<=\s)\s+(?![^<>]*</pre>)", RegexOptions.Compiled);
private readonly Stream responseStream;
public MinifyHtmlStream(Stream responseStream)
{
this.responseStream = responseStream;
}
public override void Close()
{
var minified = Encoding.UTF8.GetBytes(RegExpressionWhiteSpaces.Replace(Encoding.UTF8.GetString(ToArray()), string.Empty));
responseStream.Write(minified, 0, minified.Length);
responseStream.Flush();
base.Close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment