【问题标题】:Can download a file from firefox and chrome but not in IE可以从 Firefox 和 chrome 下载文件,但不能在 IE 中下载
【发布时间】:2012-08-29 09:09:46
【问题描述】:

我有一个带有 Web API 的 ASP.NET MVC 4 应用程序。它工作得很好。但是一个问题是 IE 不能从 web api 下载文件,而 chrome 和 firefox 可以。浏览器说

"Unable to open this internet site. The requested site is either unavailable or cannot be found."

根据IE 8 and client-side caching,看来是no-cache 设置导致了问题。所以我想在那个下载中设置私人缓存。但在 MVC 4 中,我发现 HttpResponseMessage 中没有属性“Cache”,也没有任何设置私有缓存的方法。任何人都可以展示如何做到这一点?

更新一:根据我的调试,不是缓存,而是下面代码中的`ContentDisposition'。

            HttpResponseMessage response = new HttpResponseMessage();
            response.StatusCode = HttpStatusCode.OK;
            response.Content = new StreamContent(result);
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.ms-excel");
//            response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
//              {
//                FileName = "PY75.xls"
//              };
            return response;

如果我像上面这样评论,IE 可以下载以 id 作为默认文件名的文件,但是当取消上面的评论时,它不能像上面描述的那样。知道如何解决这个问题吗?为什么 IE 无法识别 content-disposition 标头?

更新 2: 升级 IE 9 后,content-disposition 终于可以工作了,可以从 web api 下载。

【问题讨论】:

  • IE9 和 IE10 能识别content-disposition 标头吗?

标签: c# asp.net-mvc asp.net-mvc-4


【解决方案1】:

尝试添加

response.AddHeader("Content-Disposition", "attachment; filename=PY75.xls");

更新

我对此进行了更多研究,这可能是您打开和关闭流的方式的结果(在没有看到其余代码的情况下不确定。我尝试了以下方法,它对我有用,也许它会起作用给你!

    public HttpResponseMessage Get()
    {
        string path = @"PATH_TO_XLS";
        MemoryStream responseStream = new MemoryStream();

        using (Stream fileStream = File.Open(path, FileMode.Open))
        {
            fileStream.CopyTo(responseStream);
            fileStream.Close();
        }

        responseStream.Position = 0;

        HttpResponseMessage response = new HttpResponseMessage();
        response.StatusCode = HttpStatusCode.OK;
        response.Content = new StreamContent(responseStream);
        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "PY75.xls" };

        return response;
    }

唯一一次我注意到浏览器会出现问题是内存流在发送回响应之前关闭,这是有道理的,因为必须打开内存流才能将内容流回客户端。但是我注意到所有浏览器上的问题,而不仅仅是 IE。我不确定你的其余代码是如何处理这个问题的,但是如果你例如为分块 http 处理创建流的方式不同,而不是只发送可能导致它的整个文件。

【讨论】:

    【解决方案2】:

    我遇到了类似的问题,并在博客中介绍了我的解决方案here 该解决方案的要点是 Pragma=no-cache 标头会导致在 HTTPS 上时在 IE 9 及更低版本中下载失败。所以你基本上必须去掉那个标题。另外,如果有一个显式的 Cache-control 标头,并且它的值应该是 no-store,no-cache 因为相反的顺序也会导致下载失败。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-17
      • 2012-05-18
      • 2023-03-05
      • 1970-01-01
      • 2020-08-10
      • 1970-01-01
      • 2014-05-23
      • 1970-01-01
      相关资源
      最近更新 更多