我希望使用下面的代码在我的项目中实现HTML压缩。
public class CompressFilter : ActionFilterAttribute {
public override void OnActionExecuting(FilterExecutingContext filterContext)
{
HttpRequestBase request = filterContext.HttpContext.Request;
string acceptEncoding = request.Headers["Accept-Encoding"];
if (string.IsNullOrEmpty(acceptEncoding)) return;
acceptEncoding = acceptEncoding.ToUpperInvariant();
HttpResponseBase response = filterContext.HttpContext.Response;
if (acceptEncoding.Contains("GZIP"))
{
response.AppendHeader("Content-encoding", "gzip");
response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
}
else if (acceptEncoding.Contains("DEFLATE"))
{
response.AppendHeader("Content-encoding", "deflate");
response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
}
}
}
但是,我在FilterExecutingContext
上收到了错误消息。它显示错误,如code not found...
那么请给我一些建议我应该如何在我的项目中实现HTML压缩。
还有其他任何建议请告诉我。
感谢。
答案 0 :(得分:4)
OnActionExecuting
的方法签名已更改为:
public override void OnActionExecuting(ActionExecutingContext filterContext)
将FilterExecutingContext
替换为ActionExecutingContext
。
请参阅MSDN。
答案 1 :(得分:0)
为Accept编码添加验证。你使用了错误的字母大小写
接受编码,GZIP和DEFLATE
。请提供以下示例代码:
if(Request.Headers["Accept-encoding"] != null &&
Request.Headers["Accept-encoding"].Contains("gzip")) {
Response.Filter = new GZipStream(Response.Filter,
CompressionMode.Compress, true);
Response.AppendHeader("Content-encoding", "gzip");
}
else if(Request.Headers["Accept-encoding"] != null &&
Request.Headers["Accept-encoding"].Contains("deflate")) {
Response.Filter = new DeflateStream(Response.Filter,
CompressionMode.Compress, true);
Response.AppendHeader("Content-encoding", "deflate");
}
Courtsy http://www.codeproject.com/Articles/14761/HTTP-Compression-A-Quick-and-Dirty-Solution