萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

.NET 網頁輸出壓縮與最佳化:移除空白字元的 HttpModule 實作

目的與效益

移除 HTML 輸出中的多餘空白、換行、Tab,可減少 10%~30% 傳輸體積,加快頁面載入速度,並略微增加原始碼閱讀難度(非安全手段)。

實作架構:HttpModule + Response.Filter

攔截 `Render` 階段,將輸出串流包裝在自訂 `Stream` 中,於 `Flush/Close` 時進行 Regex 清理。

完整程式碼

1. 壓縮串流類別

using System.IO;
using System.Text.RegularExpressions;

public class WhitespaceFilterStream : Stream
{
    private readonly Stream _baseStream;
    private readonly MemoryStream _buffer = new MemoryStream();
    private static readonly Regex _whitespaceRegex = new Regex(
        @">\s+<|[\r\n\t]+|\s{2,}", 
        RegexOptions.Compiled | RegexOptions.Singleline);

    public WhitespaceFilterStream(Stream baseStream) => _baseStream = baseStream;

    public override void Write(byte[] buffer, int offset, int count)
    {
        _buffer.Write(buffer, offset, count);
    }

    public override void Flush()
    {
        string html = Encoding.UTF8.GetString(_buffer.ToArray());
        html = _whitespaceRegex.Replace(html, m => m.Value switch
        {
            var v when v.StartsWith(">") && v.EndsWith("<") => "><", // 標籤間空白
            var v when v.All(c => c == ' ') => " ",                // 多空白 → 單空白
            _ => ""                                                 // 換行/Tab 移除
        });

        byte[] output = Encoding.UTF8.GetBytes(html);
        _baseStream.Write(output, 0, output.Length);
        _buffer.SetLength(0); // 重置緩衝
    }

    // 以下成員委派給 _baseStream
    public override bool CanRead => _baseStream.CanRead;
    public override bool CanSeek => _baseStream.CanSeek;
    public override bool CanWrite => _baseStream.CanWrite;
    public override long Length => _baseStream.Length;
    public override long Position { get => _baseStream.Position; set => _baseStream.Position = value; }
    public override long Seek(long offset, SeekOrigin origin) => _baseStream.Seek(offset, origin);
    public override void SetLength(long value) => _baseStream.SetLength(value);
    public override int Read(byte[] buffer, int offset, int count) => _baseStream.Read(buffer, offset, count);
    public override void Close() { Flush(); _baseStream.Close(); base.Close(); }
}

2. HttpModule 註冊

public class HtmlCompressionModule : IHttpModule
{
    public void Init(HttpApplication context)
    {
        context.ReleaseRequestState += (sender, e) =>
        {
            var app = (HttpApplication)sender;
            // 僅處理 HTML 回應
            if (app.Context.Response.ContentType?.StartsWith("text/html", StringComparison.OrdinalIgnoreCase) == true)
            {
                app.Response.Filter = new WhitespaceFilterStream(app.Response.Filter);
            }
        };
    }
    public void Dispose() { }
}

3. Web.config 註冊 (IIS 7+ 整合模式)

<system.webServer>
  <modules>
    <add name="HtmlCompression" type="YourNamespace.HtmlCompressionModule" />
  </modules>
</system.webServer>

Regex 規則詳解

@">\s+<|[\r\n\t]+|\s{2,}"
  • `>\s+<`:標籤之間的空白 → `><`(保留單一空白會導致 inline 元素錯位)
  • `[\r\n\t]+`:換行、Tab → 移除
  • `\s{2,}`:連續 2 個以上空白 → 單一空白

注意:`

`、`