我有许多文件保存到光盘并使用gzip压缩,因为它们最终会在浏览器中显示。我使用ASP.NET MVC并在代码中添加以下标题
Response.AppendHeader("Content-Encoding", "gzip");
我得到以下响应标题
Cache-Control:private
Connection:Close
Content-Encoding:gzip
Content-Length:791
Content-Type:text/xml
几乎 很好。这些文件是带有UTF-16 XML声明的XML文件。
<?xml version="1.0" encoding="utf-16"?>
要在IE中正确显示,我还需要将响应编码为UTF-16。 我需要在响应中更改以使其在不破坏gzip解压缩等的情况下工作?
更新#1
还尝试添加charset标头以返回以下响应标头
Cache-Control:private
Connection:Close
Content-Encoding:gzip
Content-Length:791
Content-Type:text/xml; charset=UTF-16
然而,这打破了gzip压缩,结果是未压缩的gzip内容......
答案 0 :(得分:1)
我无法重现您描述的情景。我认为你的方法没有任何问题,这让我相信问题出在其他地方。请按照我采取的相同步骤验证您的代码中没有其他内容被破坏,然后我们可以继续调试。
我使用Visual Studio生成了一个UTF-16编码的xml文件,然后使用Total Commander将其压缩到磁盘。
发送所需响应的快捷方式将是这样的(在您的mvc控制器中)
public ActionResult Index()
{
var path = Server.MapPath("~/Content/test.xml.gz");
var result = new FilePathResult(path, "text/xml");
Response.AddHeader("Content-Encoding", "gzip");
Response.Charset = "utf-16";
return result;
}
现在,虽然这可行,但它不是在MVC中这样做的惯用方法,而且有点不受欢迎。正确的方法是实现自己的操作结果,并在结果执行时让结果设置相应的标题。使用这种方法,可以使用“干净”的http上下文对结果进行后处理。
所以,这是一个这样的行动结果的例子。
public class BinaryFileResult : FilePathResult
{
public string Charset { get; set; }
public string ContentEncoding { get; set; }
public BinaryFileResult(string fileName, string contentType) : base(fileName, contentType) { }
protected override void WriteFile(HttpResponseBase response)
{
if (this.Charset != null)
response.Charset = this.Charset;
if (this.ContentEncoding != null)
response.AppendHeader("Content-Encoding", this.ContentEncoding);
base.WriteFile(response);
}
}
这是我们的工具带,我们可以将动作方法减少到类似的东西
public ActionResult Index()
{
return new BinaryFileResult(Server.MapPath("~/Content/test.xml.gz"), "text/xml")
{
Charset = "utf-16",
ContentEncoding = "gzip"
};
}
使用这两种方法,我可以在IE9中查看正确解码的xml文件。快去,让我知道它是如何工作的。
<强>更新强> 这是我用来测试它的文件。正如我所说,他们在我的机器上的IE9上产生了适当的结果。