我有一个带有 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 ,看起来是无缓存设置导致了问题。所以我想在该下载中设置私有(private)缓存。但是在 MVC 4 中,我发现 HttpResponseMessage 中没有属性“Cache”,也没有任何设置私有(private)缓存的方法。任何人都可以展示如何做到这一点吗?
更新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 header ?
更新 2: 升级 IE 9 后,content-disposition 终于可以使用了,可以从 web api 下载。
最佳答案
尝试添加
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 创建流,而不是只发送可能导致它的整个文件。
关于c# - 可以从 firefox 和 chrome 下载文件,但不能在 IE 中下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12268035/