我一直在为我的 MVC 操作使用压缩过滤器,如下所述:
http://msdn.microsoft.com/en-us/magazine/gg232768.aspx
我试图重新利用代码为 Web API 做类似的事情,但我遇到了一个障碍:
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;
}
有什么想法可以将压缩流分配给响应的内容吗?
我应该指出这是托管在我无法控制的 IIS 6.0 中。