为什么IE无法从Response.Write服务我的CSV文件?

时间:2010-11-09 12:46:49

标签: asp.net internet-explorer header download content-type

我最近开发了一个列出一系列报告的Web用户控件。当用户点击报告时,它使用以下代码在响应流中回送CSV文件:

 Response.Clear();

 Response.ContentType = "text/CSV";

 Response.CacheControl = "no-cache";
 Response.AddHeader("Pragma", "no-cache");
 Response.Expires = -1;

 Response.AddHeader("Pragma", "must-revalidate");
 Response.AddHeader("Cache-Control", "must-revalidate");
 Response.AddHeader("Accept-Header", csvResults.Length.ToString());
 Response.AddHeader("Content-Length", csvResults.Length.ToString());
 Response.AddHeader("content-disposition", "attachment; filename=test.csv");
 Response.Write(csvResults.ToString());
 Response.Flush();
 Response.End();

该代码最初在所有浏览器中都运行良好。然后客户端要求为站点使用SSL。作为其中的一部分,我介绍了一个全局处理程序,用于将所有请求的协议从HTTP更新为HTTPS:

protected void Application_BeginRequest(Object sender, EventArgs e)
    {
        string requestURL = Request.Url.ToString().ToLower();
        if (requestURL.StartsWith("http://"))
        {
            Response.Redirect(requestURL.Replace("http:", "https:"));
        }
    }

但是,由于使用SSL保护网站,因此CSV文件下载不再适用于IE,尽管它们可以继续用于Firefox / Chrome / Safari。

为了让文件响应正常工作,IE中是否有一些我缺少的东西?

我从IE收到的消息是:

  

“Internet Explorer无法下载   来自......的Reports.aspx ......

     

Internet Explorer无法打开   这个互联网网站。请求的网站   要么不可用,要么不能   找到。请稍后再试。“

更新:

以下是从页面请求返回的一些示例fiddler输出,看起来它正常服务。为什么IE不明白它只是一个文件?

HTTP/1.1 200 OK
Date: Tue, 09 Nov 2010 14:23:50 GMT
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
X-AspNet-Version: 4.0.30319
Pragma: no-cache
Pragma: must-revalidate

content-disposition: attachment; filename="test.csv"
Cache-Control: no-cache
Pragma: no-cache
Expires: -1
Content-Length: <length value would be here>
Content-Type: text/CSV

"COL1","COL2","COL3"
"VAL1","VAL2","VAL3"
"VAL1","VAL2","VAL3"
"VAL1","VAL2","VAL3"

4 个答案:

答案 0 :(得分:7)

花了好几个小时试图解决这个问题后,我终于想出了一个解决方案。

幸运的是,我设法遇到a post by Eric Law关于IE与HTTPS和包含缓存指令的响应头之间不兼容的问题。

现在确保清除了所有响应标头,并且没有对响应执行缓存说明,然后文件再次作为下载开始响应。

答案 1 :(得分:2)

正如布莱恩所说,Eric Law的帖子是解决这个谜团的关键......

快速解决方案是:

Response.ClearHeaders();
Response.AddHeader("Cache-Control", "no-store, no-cache");

(无法解释的事实是'no-store'必须才能'no-cache')

答案 2 :(得分:0)

不确定这是否能解决您的问题,但我会仔细检查csv文件的请求是否最初是使用https进行的,以避免在Application_BeginRequest中进行重定向。

您可以使用Fiddler查看所有正在发出的请求,这会告诉您是否正在点击重定向代码。

答案 3 :(得分:0)

使用IIS 7.5+使用URL Rewrite extention添加出站规则以去除Cache-Control标头中的“no-store”值,并剥离Pragma标头(这是永远不需要的)。这个规则集可以解决问题:

<outboundRules>
    <rule name="Always Remove Pragma Header">
        <match serverVariable="RESPONSE_Pragma" pattern="(.*)" />
        <action type="Rewrite" value="" />
    </rule>
    <rule name="Remove No-Store for Attachments">
        <conditions>
            <add input="{RESPONSE_Content-Disposition}" pattern="attachment" />
        </conditions>
        <match serverVariable="RESPONSE_Cache-Control" pattern="no-store" />
        <action type="Rewrite" value="max-age=0" />
    </rule>
</outboundRules>