我已經使用壓縮過濾器對我的MVC的行動一直爲這裏詳述:的Web API壓縮過濾器
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託管的,我不能控制它。
在ASP.NET網頁API更好的方法是'DelegatingHandler'並已有一個答案描述解決方案http://stackoverflow.com/questions/10443588/mvc4-webapi-compress-get-method-response – tpeczek
過濾器允許您只指定某些webapi操作...不DelegatingHandler強制您壓縮所有操作? –