這是一個古老的問題,但我會拋出我的解決方案,以防其他人受益。
我有一個「縮小」過濾器使用大部分工作正則表達式。在pre
和textarea
標籤中存在空格時,它失敗。我前幾天因爲這個問題而碰壁,所以我花了大約三天的時間閱讀別人的嘗試並嘗試了我的想法。最後,我決定使用HtmlAgilityPack解析HTML並從中刪除空白節點。因爲pre
和textarea
元素中的空白不被HAP認爲是空白,所以它對我有利,並且完全符合我的要求。我在開始時遇到了麻煩,因爲HTML是以塊的形式發送的,但我通過緩衝它直到完成才解決了它。這是我的代碼,以防其他人受益。
請注意,該過濾器適用於我的應用程序(ASP.NET MVC 5)。理想情況下,應該在發佈期間進行縮小處理,以避免需要這樣的過濾器。最後,@naivists在他的回答中指出,GZIP壓縮回應將比縮小效果更好,但我稍微不同意他的看法。是的,它會的,但縮小確實會減少對此的反應。在使用CSS進行樣式設計時,它的真正亮點在於,因爲現在您不必擔心空白碰撞和放錯元素,而必須使用邊距/填充/定位技巧來糾正它。 [ASP.NET應用的壓縮HTML輸出]的
[AttributeUsage(AttributeTargets.Class, Inherited = false)]
internal sealed class MinifyHtmlAttribute :
ActionFilterAttribute {
public override void OnActionExecuted(
ActionExecutedContext filterContext) {
if (filterContext == null
|| filterContext.IsChildAction) {
return;
}
filterContext.HttpContext.Response.Filter = new MinifyHtmlStream(filterContext.HttpContext);
}
}
internal sealed class MinifyHtmlStream :
MemoryStream {
private readonly MemoryStream BufferStream;
private readonly HttpContextBase Context;
private readonly Stream FilterStream;
public MinifyHtmlStream(
HttpContextBase httpContextBase) {
BufferStream = new MemoryStream();
Context = httpContextBase;
FilterStream = httpContextBase.Response.Filter;
}
public override void Flush() {
BufferStream.Seek(0, SeekOrigin.Begin);
if (Context.Response.ContentType != "text/html") {
BufferStream.CopyTo(FilterStream);
return;
}
var document = new HtmlDocument();
document.Load(BufferStream);
var spans = document.DocumentNode.Descendants().Where(
d =>
d.NodeType == HtmlNodeType.Element
&& d.Name == "span").SelectMany(
d => d.ChildNodes.Where(
cn => cn.NodeType == HtmlNodeType.Text)).ToList();
// Some spans have content that needs to be trimmed.
foreach (var span in spans) {
span.InnerHtml = span.InnerHtml.Trim();
}
var nodes = document.DocumentNode.Descendants().Where(
d =>
(d.NodeType == HtmlNodeType.Text
&& d.InnerText.Trim().Length == 0)
|| (d.NodeType == HtmlNodeType.Comment
&& d.InnerText.Trim() != "<!DOCTYPE html>")).Select(
d => d).ToList();
foreach (var node in nodes) {
node.Remove();
}
document.Save(FilterStream);
}
public override void Write(
byte[] buffer,
int offset,
int count) {
BufferStream.Write(buffer, offset, count);
}
}
可能重複(http://stackoverflow.com/questions/255008/minify-html-output-of-asp-net-application) – obayhan 2015-05-06 09:55:07