Last active
August 7, 2017 18:48
-
-
Save SebastianStehle/768e09a041be3b255a171f975209abe2 to your computer and use it in GitHub Desktop.
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
[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