.Net实现GZip压缩网页,C#设置开启GZip压缩
以二进制输入缓冲器和GZIP编码输入
检查是否gzip是支持的客户端
using System;
using System.Web;
using System.IO;
using System.Text;
using System.IO.Compression;
using System.Text.RegularExpressions;
namespace yunjsonWeb
{
public class GZipHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
HttpContext Context = HttpContext.Current;
HttpRequest Request = Context.Request;
HttpResponse Response = Context.Response;
string AcceptEncoding = Request.Headers["Accept-Encoding"];
// *** 首先检查是否gzip是支持的客户端
bool UseGZip = false;
if (!string.IsNullOrEmpty(AcceptEncoding) &&
AcceptEncoding.ToLower().IndexOf("gzip") > -1)
UseGZip = true;
// *** 创建一个cachekey并检查是否存在
string CacheKey = Request.QueryString.ToString() + UseGZip.ToString();
byte[] Output = Context.Cache[CacheKey] as byte[];
if (Output != null)
{
// *** 是的-读缓存和发送给客户端
SendOutput(Output, UseGZip);
return;
}
// ***加载脚本文件
string Script = "";
StreamReader sr = new StreamReader(context.Server.MapPath(Request["src"]));
Script = sr.ReadToEnd();
// *** 现在我们准备开始创建输出
// *** 除非至少有8K不gzip
if (UseGZip && Script.Length > 6000)
Output = GZipMemory(Script);
else
{
Output = Encoding.ASCII.GetBytes(Script);
UseGZip = false;
}
// *** 添加到缓存中的一天
Context.Cache.Add(CacheKey, Output, null, DateTime.UtcNow.AddDays(1), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.High, null);
// *** 写出合适的客户端缓存设置的响应对象
this.SendOutput(Output, UseGZip);
}
/// <summary>
/// 将输出发送到客户端使用适当的缓存设置。
/// 内容应该已经准备好要发送的编码和二进制。
/// </summary>
/// <param name="Output"></param>
/// <param name="UseGZip"></param>
private void SendOutput(byte[] Output, bool UseGZip)
{
HttpResponse Response = HttpContext.Current.Response;
Response.ContentType = "application/x-javascript";
if (UseGZip)
Response.AppendHeader("Content-Encoding", "gzip");
//if (!HttpContext.Current.IsDebuggingEnabled)
// {
Response.ExpiresAbsolute = DateTime.UtcNow.AddYears(1);
Response.Cache.SetLastModified(DateTime.UtcNow);
Response.Cache.SetCacheability(HttpCacheability.Public);
// }
Response.BinaryWrite(Output);
Response.End();
}
/// <summary>
///以二进制输入缓冲器和GZIP编码输入
/// </summary>
/// <param name="Buffer"></param>
/// <returns></returns>
public static byte[] GZipMemory(byte[] Buffer)
{
MemoryStream ms = new MemoryStream();
GZipStream GZip = new GZipStream(ms, CompressionMode.Compress);
GZip.Write(Buffer, 0, Buffer.Length);
GZip.Close();
byte[] Result = ms.ToArray();
ms.Close();
return Result;
}
public static byte[] GZipMemory(string Input)
{
return GZipMemory(Encoding.ASCII.GetBytes(Input));
}
public bool IsReusable
{
get
{
return false;
}
}
}
}