Edi*_*ang 8 asp.net asp.net-mvc gzip action-filter
我想在我的网站上使用G-ZIP,我用Google搜索了以下代码:
public class CompressAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var acceptEncoding = filterContext.HttpContext.Request.Headers["Accept-Encoding"];
if (!string.IsNullOrEmpty(acceptEncoding))
{
acceptEncoding = acceptEncoding.ToLower();
var 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);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
当我将属性设置为Controller或Action时,它工作正常.
[Compress]
public class PostController : Controller
Run Code Online (Sandbox Code Playgroud)
我不想在每一段代码上都这样做,所以我在这里注册了这个属性
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new CompressAttribute());
}
Run Code Online (Sandbox Code Playgroud)
但是当我运行应用程序时,这行代码出现异常:
response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
Run Code Online (Sandbox Code Playgroud)
response.Filter为null.
我想知道为什么会这样,以及如何解决这个问题.谢谢!
- 更新:
我发现仅当控制器包含子操作并且正在调用它时才会发生异常.
我的解决方案是过滤所有儿童行为.
if (filterContext.IsChildAction) return;
Run Code Online (Sandbox Code Playgroud)
在方法的顶部使用此代码.
public class CompressAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.IsChildAction) return;
...
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2016 次 |
| 最近记录: |