3

我有一个带有 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 和客户端缓存,看起来是 no-cache 设置导致了问题。所以我想在那个下载中设置私人缓存。但在 MVC 4 中,我发现 HttpResponseMessage 中没有属性“Cache”,也没有任何设置私有缓存的方法。有人可以展示如何做到这一点吗?

更新1:根据我的调试,它不是缓存,而是以下代码中的“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 下载。

4

2 回答 2

2

尝试添加

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;
    }

The only time I noticed that the browsers would have issues is when the memory stream was closed before sending the response back, which would make sense as the memory stream has to be open to stream the content back to the client. However I noticed the problem on all browsers not just IE. I'm not sure how the rest of your code is handling that, but if you for example handle creating the stream differently for chunked http vs just sending the whole file that could cause it.

于 2012-10-08T16:24:19.610 回答
2

I faced a similar problem and blogged about my solution here The jist of the solution is that a Pragma=no-cache header causes downloads to fail in IE 9 and below when on HTTPS. So you basically have to strip off that header. Also, if there's an explicit Cache-control header, and it should have the value as no-store, no-cache as the reverse order would also cause downloads to fail.

于 2014-03-13T13:38:24.347 回答