ASP.NET MVC - 在RegisterGlobalFilters使用ActionFilterAttribute时Response.Filter为空() [英] ASP.NET MVC - Response.Filter is null when using ActionFilterAttribute in RegisterGlobalFilters()
问题描述
我想用G-ZIP在我的网站,我用Google搜索以下code:
I want to use G-ZIP on my website, I googled the following code:
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);
}
}
}
}
在我的属性设置为一个Controller或Action它工作正常。
It works fine when I set the attribute to a Controller or an Action.
[Compress]
public class PostController : Controller
我不想manully做到这一点的每一块code,所以我注册
I don't want to manully do this on every piece of code, so I registered this attribute in
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new CompressAttribute());
}
但是当我运行应用程序,异常就在这条线code的:
But when I run the application, exception came on this line of code:
response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
在response.Filter为null。
the response.Filter is null.
我想知道为什么发生这种情况,如何解决这个问题。谢谢!
I want to know why this is happening and how to solve this. Thanks!
- 更新:
我发现,发生异常,只有当控制器包含一个孩子的行动,而且它被调用。
推荐答案
我的解决办法是过滤所有孩子的行动。
My solution was to filter all child action.
if (filterContext.IsChildAction) return;
在你的方法顶部使用此code。
Use this code on the top of your method.
public class CompressAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.IsChildAction) return;
...
}
}
这篇关于ASP.NET MVC - 在RegisterGlobalFilters使用ActionFilterAttribute时Response.Filter为空()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!