[英]Response.Filter breaks encoding randomly
我有一个使用 WCF 的简单 html 和 javascript 客户端应用程序(不是 asp.net 应用程序)。 我需要更改静态页面中的一些变量,因此我认为 Response.Filter 是最适合我的选项。 我写了几行代码并且它起作用了,但是在我的浏览器上刷新了几次之后,我注意到有一个错误。 有些东西破坏了页面的编码。 我究竟做错了什么?
Global.asax:(我也尝试过其他事件,但没有任何变化)
private void Application_PostReleaseRequestState(object sender, System.EventArgs e)
{
if (Request.CurrentExecutionFilePathExtension.EndsWith(".html") || Request.CurrentExecutionFilePathExtension.EndsWith(".js"))
{
Response.Filter = new ContentFilter(Response.Filter);
}
}
内容过滤器.cs
public class ContentFilter : MemoryStream
{
private Stream outputStream = null;
private Regex version = new Regex("%version%", RegexOptions.Compiled | RegexOptions.Multiline);
public ContentFilter(Stream output)
{
outputStream = output;
}
public override void Write(byte[] buffer, int offset, int count)
{
// Convert the content in buffer to a string
string contentInBuffer = UTF8Encoding.UTF8.GetString(buffer);
contentInBuffer = version.Replace(contentInBuffer, "2");
outputStream.Write(UTF8Encoding.UTF8.GetBytes(contentInBuffer), offset, UTF8Encoding.UTF8.GetByteCount(contentInBuffer));
}
}
注意:我在 Windows 8 上使用 IIS 7.5。
当我在 Write 方法中调试 ContentFilter.cs 作为 contentInBuffer 变量的值时,我看到了这些。 我在 IIS 设置中默认使用 GZIP 压缩,也许这就是问题所在。
` \\b\\0\\0\\0\\0\\0\\0 Z n w3\\b( \\" VD I 8A۵ a r ,m \\t >@ t \\n(P / + ] $ B 3s | _ n。 ...
您忽略了传递给Write
实现的offset
和count
。 使用也接受索引和计数的GetString
覆盖可能会有所帮助。
但是,恐怕还有其他一些问题。 您在Write
函数中收到的数据将以块的形式到达。 如果第一个块以“%vers”结尾,第二个块以“ion%”开头,会发生什么?
此外,由于非 ASCII 字符在 UTF-8 中表示为多个字节,因此单个 Unicode 字符可能会“分散”到对Write
两个后续调用中,这将导致UTF8Encoding.UTF8.GetString
失败。
我也遇到过这个问题,是IIS静态内容GZip压缩造成的。 为了防止损坏,我通过以下 Web.Config 条目禁用了静态压缩:
<system.webServer>
<urlCompression doStaticCompression="false" />
</system.webServer>
事实证明,默认情况下不会压缩小于 2700 字节的文件(请参阅 IIS 压缩设置),因此您只会看到静态内容大于该值的情况。
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.