Asp.. Net MVC 4 API:在IE8中下载docx失败

本文关键字:IE8 下载 docx 失败 Net MVC API Asp | 更新日期: 2023-09-27 18:05:31

我正在数据库中存储文档,并有一个用于下载文档的api。

docx和xlsx的下载在IE9,Chrome和FF中运行良好,但在真正的IE8中失败。(ie9在IE8模式下也可以使用)

我得到的错误信息如下:

无法从idler2下载393 .

无法打开此Internet站点。请求的站点是不可用或无法找到。请稍后再试。

具有以下响应头:Http/1.1 200 okcache - control: no - cache编译指示:no - cache

Content-Length: 10255
Content-Type: application/octet-stream
Expires: -1
Server: Microsoft-IIS/7.5
Content-Disposition: attachment; filename=document.docx
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Sat, 23 Mar 2013 11:30:41 GMT
这是我的api方法:
public HttpResponseMessage GetDocumentContent(int id)
{
    Document document = Repository.StorageFor<Client>().GetDocument(id);
    HttpResponseMessage response = Request.CreateResponse(System.Net.HttpStatusCode.OK);
    response.Content = new ByteArrayContent(document.GetBuffer());
    response.Content.Headers.ContentLength = document.GetBuffer().Length;
    response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
    {
        //FileName = document.GetFileName(),
        FileName = "document.docx",
        DispositionType = "attachment"
    };
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");            
    return response;
}

我已经尝试了相当多的内容处置和内容标题的变化,但没有运气…

Asp.. Net MVC 4 API:在IE8中下载docx失败

我假设您在SSL下遇到过这种情况。如果是这样,那么这是一个已知的问题。本文讨论的是Office文档,但这个问题适用于所有文件类型。

那篇文章的解决方案是删除no-cache头,但还有更多。当IE8通过SSL与Web站点通信时,IE8强制执行任何无缓存请求。如果标头或标头存在,IE8不会缓存该文件。因此,它无法打开文件。所有这些都是针对IE5到IE8的。

在MVC Web API中,它实际上采取了另一个步骤。因为你正在创建一个新的HttpResponseMessage,你还必须在消息的头上创建一个CacheControlHeaderValue。您不需要设置任何头部属性,只需实例化一个新属性即可。头文件将默认为需要的内容,因此您不需要更改属性。

public HttpResponseMessage GetDocumentContent(int id)
{
    Document document = Repository.StorageFor<Client>().GetDocument(id);
    HttpResponseMessage response = Request.CreateResponse(System.Net.HttpStatusCode.OK);
    response.Headers.CacheControl = new CacheControlHeaderValue(); // REQUIRED     
    response.Content = new ByteArrayContent(document.GetBuffer());
    response.Content.Headers.ContentLength = document.GetBuffer().Length;
    response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
    {
        FileName = "document.docx"
    };
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
    return response;
}

我有一个确切的问题,但这解决了它。

到目前为止,我发现的唯一解决方案是将文件存储在临时文件夹中并返回下载url。(javascript)客户端可以打开一个新窗口。

不是很好,但似乎MVC 4 API带来了一些限制。