public class CompressionSettings
{
private string preferredAlgorithm = "gzip";
private StringCollection contentTypes = new StringCollection();
public StringCollection ContentTypes
{
get { return contentTypes; }
set { contentTypes = value; }
}
public string PreferredAlgorithm
{
get { return preferredAlgorithm; }
set { preferredAlgorithm = value; }
}
public CompressionSettings()
{
ContentTypes.Add("text/html");
ContentTypes.Add("text/plain");
}
public static CompressionSettings GetCompressionSettings()
{
if (HttpContext.Current.Cache["CompressionSettings"] == null)
{
CompressionSettings compressionSettings = new CompressionSettings();
if (ConfigurationManager.GetSection("CompressionSettings") != null)
{
compressionSettings = (CompressionSettings)ConfigurationManager.GetSection
("CompressionSettings");
}
HttpContext.Current.Cache.Insert("CompressionSettings",compressionSettings);
}
return (CompressionSettings)HttpContext.Current.Cache["CompressionSettings"];
}
public bool IsContentTypeCompressed(string contentType)
{
foreach (string s in contentTypes)
{
if (String.Compare(s, contentType, true) == 0)
{
return true;
}
}
return false;
}
public String GetCompressionType(string acceptEncoding)
{
bool foundDeflate = false;
bool foundGZip = false;
string[] schemes = acceptEncoding.Split(',');
for (int i = 0; i < schemes.Length; i++)
{
string acceptEncodingValue = schemes[i].Trim().ToLower();
if (acceptEncodingValue.StartsWith("deflate")&& canAcceptQuality(acceptEncodingValue))
{
foundDeflate = true;
}
else if ((acceptEncodingValue.StartsWith("gzip")|| acceptEncodingValue.StartsWith("x-gzip"))
&& canAcceptQuality(acceptEncodingValue))
{
foundGZip = true;
}
else if (acceptEncodingValue.StartsWith("*") && canAcceptQuality(acceptEncodingValue))
{
foundGZip = true;
foundDeflate = false;
}
}
if (preferredAlgorithm == "gzip" && foundGZip)
{
return "gzip";
}
if (preferredAlgorithm == "deflate" && foundDeflate)
{
return "deflate";
}
if (foundDeflate) return "deflate";
if (foundGZip) return "gzip";
return "none";
}
/***********************************************
* System.IO.Compression does not support compression
* ratio so we will just check header to see if specified
* compression level is above zero.
* ********************************************/
bool canAcceptQuality(string acceptEncodingValue)
{
int qParam = acceptEncodingValue.IndexOf("q=");
float val = 1.0f;
if (qParam >= 0)
{
try
{
val = float.Parse(acceptEncodingValue.Substring(qParam + 2,
acceptEncodingValue.Length - (qParam + 2)));
}
catch (FormatException)
{
}
}
return (val > 0.0f);
}
}