在使用“FilterExecutingContext”时出现错误,如何使用ActionFilterAttribute类的
本文关键字:错误 何使用 类的 ActionFilterAttribute FilterExecutingContext | 更新日期: 2023-09-27 18:11:18
我想在我的项目中使用下面的代码实现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压缩。还有什么建议请告诉我。
谢谢。
将OnActionExecuting
的方法签名修改为:
public override void OnActionExecuting(ActionExecutingContext filterContext)
用ActionExecutingContext
代替FilterExecutingContext
查看MSDN。
添加Accept编码验证。
的大小写不正确Accept-encoding, GZIP and 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