private void Application_BeginRequest(object sender, EventArgs e)
{
var context = HttpContext.Current;
var request = context.Request;
var response = context.Response;
ResponseCompressionType compressionType = this.GetCompressionMode(request);
if (compressionType != ResponseCompressionType.None)
{
response.AppendHeader("Content-Encoding", compressionType.ToString().ToLower());
if (compressionType == ResponseCompressionType.GZip)
{
response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
}
else
{
response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
}
}
}
private ResponseCompressionType GetCompressionMode(HttpRequest request)
{
string acceptEncoding = request.Headers["Accept-Encoding"];
if (string.IsNullOrEmpty(acceptEncoding))
{
return ResponseCompressionType.None;
}
acceptEncoding = acceptEncoding.ToUpperInvariant();
if (acceptEncoding.Contains("GZIP"))
{
return ResponseCompressionType.GZip;
}
else if (acceptEncoding.Contains("DEFLATE"))
{
return ResponseCompressionType.Deflate;
}
else
{
return ResponseCompressionType.None;
}
}
private enum ResponseCompressionType { None, GZip, Deflate }