使用压缩操作过滤器,服务器错误消息会清除内容编码标头并呈现为乱码
当我使用压缩过滤器并收到错误时,错误页面只是乱码。问题似乎是当 IIS 传输到错误页面时,压缩过滤器仍然有效,但标头被清除。如果没有“Content-encoding:gzip”标头,浏览器只会显示原始 gzip 压缩的二进制数据。
我正在使用 IIS7.5、ASP.NET MVC 2 Preview 2 和 ActionFilter,如下所示:
public class CompressResponseAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var request = filterContext.HttpContext.Request;
var response = filterContext.HttpContext.Response;
var acceptEncoding = request.Headers["Accept-Encoding"];
if (string.IsNullOrEmpty(acceptEncoding))
return;
acceptEncoding = acceptEncoding.ToLowerInvariant();
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);
}
}
}
还有其他人经历过这种情况吗?
When I'm using a compression filter and get an error, the error page is just gibberish characters. The problem seems to be that when IIS transfers to the error page the compression filter is still in effect, but the headers are cleared. Without the "Content-encoding: gzip" header the browser just displays the raw gzipped binary data.
I'm using IIS7.5, ASP.NET MVC 2 Preview 2 and an ActionFilter that looks like this:
public class CompressResponseAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var request = filterContext.HttpContext.Request;
var response = filterContext.HttpContext.Response;
var acceptEncoding = request.Headers["Accept-Encoding"];
if (string.IsNullOrEmpty(acceptEncoding))
return;
acceptEncoding = acceptEncoding.ToLowerInvariant();
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);
}
}
}
Anyone else experienced this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
更新:
我偶然发现了 Rick Strahl 的关于这个问题和其他压缩问题的博客文章。参见这里:
http://www.west-wind .com/weblog/posts/2011/May/02/ASPNET-GZip-Encoding-Caveats
他的解决方案似乎更可靠,是将以下内容放入 Global.asax.cs 中:
原始答案:
我通过在 OnResultExecuting 而不是 OnActionExecuting 中应用压缩来修复此问题。
Update:
I stumbled upon Rick Strahl's blog post on this and other problems with compression. See here:
http://www.west-wind.com/weblog/posts/2011/May/02/ASPNET-GZip-Encoding-Caveats
His solution, which seems more reliable, is to put the following in Global.asax.cs:
Original answer:
I fixed this by applying the compression in OnResultExecuting instead of OnActionExecuting.