与IIS站点压缩资源文件相比,通过APP方式压缩,相对比较灵活,当然采用前端硬件层缓存压缩机制或第三方组件除外。
1、自定义压缩文件过滤
2、附加处理业务逻辑、计算
以下是实现代码:
/// <summary>
/// 页面压缩处理
/// </summary>
public class CompressionModule : IHttpModule
{
#region -- Attributes --
private DateTime _StartTime;
private bool IsBig5 = false;
private static string ipKey = "_forbidIpKey";
private static int forbidTime = 3 * 60;//3小时
public static int timeCountIp = 3;//10分钟
public static string key = "encodingNullIPList";
#endregion
#region -- Constructor --
public CompressionModule()
{
}
#endregion
#region -- IHttpModule Members --
void IHttpModule.Dispose()
{
}
void IHttpModule.Init(HttpApplication context)
{
//if (PayConfig.EnableCompressPage == "1")
//{
// context.BeginRequest += new EventHandler(context_BeginRequest);
//}
}
#endregion
#region Compression
private const string GZIP = "gzip";
private const string DEFLATE = "deflate";
/// <summary>
/// Handles the BeginRequest event of the context control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
void context_BeginRequest(object sender, EventArgs e)
{
string url = HttpContext.Current.Request.Url.ToString().ToLower();
string fileName = GlobalItem.DeriveFileName(url).ToLower();
string page = LinQHelper.GetConfig("CompressPage").ToLower();
if (page.Length == 0 || page.IndexOf(fileName) < 0)
{
return;
}
HttpApplication app = sender as HttpApplication;
//压缩aspx页面
if (app.Request.Url.ToString().Contains(".aspx"))
{
//是否支持压缩协议
if (IsEncodingAccepted(GZIP))
{
app.Response.Filter = new GZipStream(app.Response.Filter, CompressionMode.Compress);
SetEncoding(GZIP);
}
else if (IsEncodingAccepted(DEFLATE))
{
app.Response.Filter = new DeflateStream(app.Response.Filter, CompressionMode.Compress);
SetEncoding(DEFLATE);
}
}
}
/// <summary>
/// Checks the request headers to see if the specified
/// encoding is accepted by the client.
/// </summary>
private static bool IsEncodingAccepted(string encoding)
{
return HttpContext.Current.Request.Headers["Accept-encoding"] != null
&& HttpContext.Current.Request.Headers["Accept-encoding"].Contains(encoding);
}
/// <summary>
/// Adds the specified encoding to the response headers.
/// </summary>
/// <param name="encoding"></param>
private static void SetEncoding(string encoding)
{
HttpContext.Current.Response.AppendHeader("Content-encoding", encoding);
}
#endregion
}