ResponseWrapper.cs
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using System.Text.RegularExpressions;
/// <summary>
/// ResponseWrapper 的摘要描述
/// </summary>
public class ResponseWrapper : Stream
{
private Stream _stream;
public ResponseWrapper(Stream stream)
{
this._stream = stream;
}
protected Stream BaseStream { get { return this._stream; } }
public override bool CanRead { get { return false; } }
public override bool CanSeek { get { return false; } }
public override bool CanWrite { get { return this._stream.CanWrite; } }
public override long Length { get { throw new NotSupportedException(); } }
public override long Position
{
get { throw new NotSupportedException(); }
set { throw new NotSupportedException(); }
}
public override long Seek(long offset, System.IO.SeekOrigin direction)
{
throw new NotSupportedException();
}
public override void SetLength(long length)
{
throw new NotSupportedException();
}
public override void Close()
{
this._stream.Close();
}
public override void Flush()
{
this._stream.Flush();
}
public override int Read(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
string outputData = System.Text.Encoding.UTF8.GetString(buffer);
outputData = Regex.Replace(outputData, ">\\s+<", "><", RegexOptions.Multiline); // replace all white space between tags
//outputData = Regex.Replace(outputData, "\\s\\s+", " ", RegexOptions.Singleline); // replace all white space to single one
byte[] outData = System.Text.Encoding.UTF8.GetBytes(outputData);
this._stream.Write(outData, 0, outData.GetLength(0));
}
}
Global.asax
<%@ Application Language="C#" %>
<script RunAt="server">
void Application_Start(object sender, EventArgs e)
{
// 應用程式啟動時執行的程式碼
}
void Application_End(object sender, EventArgs e)
{
// 應用程式關閉時執行的程式碼
}
void Application_Error(object sender, EventArgs e)
{
// 發生未處理錯誤時執行的程式碼
}
void Session_Start(object sender, EventArgs e)
{
// 啟動新工作階段時執行的程式碼
}
void Session_End(object sender, EventArgs e)
{
// 工作階段結束時執行的程式碼。
// 注意: 只有在 Web.config 檔將 sessionstate 模式設定為 InProc 時,
// 才會引發 Session_End 事件。如果將工作階段模式設定為 StateServer
// 或 SQLServer,就不會引發這個事件。
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
if (this.Response.ContentType == "text/html" // 限定輸出類型
&& this.Request.Url.AbsolutePath.EndsWith(".aspx") // 限定請求的url
&& this.Request.HttpMethod == "GET") // 限定httpmethod
this.Response.Filter = new ResponseWrapper(this.Response.Filter);
}
</script>