I've been using the compression filter for my MVC actions as detailed here:
http://msdn.microsoft.com/en-us/magazine/gg232768.aspx
I've tried to re-purpose the code to do something similar for Web API, but I've hit a roadblock:
public class CompressAPIAttribute : System.Web.Http.Filters.ActionFilterAttribute
{
public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext filterContext)
{
var preferredEncoding = GetPreferredEncoding(filterContext.Request);
Stream compressedStream = null;
// Compress the response accordingly
var response = filterContext.Response;
response.Headers.Add("Content-encoding", preferredEncoding.ToString());
if (preferredEncoding == CompressionScheme.Gzip)
{
response.Content = new GZipStream(compressedStream, CompressionMode.Compress); //THIS WON'T WORK
}
if (preferredEncoding == CompressionScheme.Deflate)
{
response.Content = new DeflateStream(compressedStream, CompressionMode.Compress); //THIS WON'T WORK
}
return;
}
enum CompressionScheme
{
Gzip = 0,
Deflate = 1,
Identity = 2
}
private CompressionScheme GetPreferredEncoding(HttpRequestMessage request)
{
var acceptableEncoding = request.Headers.AcceptEncoding;
if (acceptableEncoding.Where(h => h.Value.Contains("gzip")).Count() > 0)
return CompressionScheme.Gzip;
if (acceptableEncoding.Where(h => h.Value.Contains("deflate")).Count() > 0)
return CompressionScheme.Deflate;
return CompressionScheme.Identity;
}
Any ideas how I can assign a compressed stream to the response's content?
I should point out this is being hosted in IIS 6.0, which I do not control.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…