.NET - 使用“Response.BinaryWrite()”使IE11关闭

本文关键字:IE11 关闭 BinaryWrite 使用 Response NET | 更新日期: 2023-09-27 18:37:26

我有一个 ASP.NET 页面和一个c#方法,该方法获取(excel文件)的内存流,然后使用HTTPResponse类将该文件以二进制形式流式传输到浏览器。

    public static void WriteStreamToBrowser(MemoryStream streamExcelFile, string filename, bool isResponseEnd = false)
    {
        System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response;
        Response.ContentType = "application/vnd.ms-excel";
        Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", filename));
        Response.Clear();
        Response.BinaryWrite(streamExcelFile.GetBuffer());
    }

现在,当我在Firefox或Chrome中使用 asp.net 页面时,此方法可以正常工作。它们巧妙地触发了网站的"是否要下载此文件"功能。

但是,当使用IE11时,浏览器窗口会立即关闭,但实际上会弹出并保留"是否要下载此文件?"对话框。

猜IE在响应方法方面需要一些特殊处理,但我无法弄清楚我做错了什么。

如何更改上述方法,使其也适用于IE11?

--

如果您需要任何额外的细节,请告诉我!

编辑:

值得一提的是,调试不会引发任何异常。

此外,弹出的对话框实际上是下载历史记录。

编辑2:

我试图遵循其他指南的一些建议并添加了一些东西。不过,结果是一样的。

    public static void WriteStreamToBrowser2(MemoryStream streamExcelFile, string filename, bool isUseNewExcel = true)
    {
        System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response;
        string contentType = isUseNewExcel ? "application/vnd.ms-excel" : "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        Response.Clear();
        Response.Buffer = true;
        Response.ContentType = "application/vnd.ms-excel";
        Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", filename));
        Response.AddHeader("content-length", streamExcelFile.Length.ToString());
        Response.AddHeader("content-type", contentType);
        Response.BinaryWrite(streamExcelFile.GetBuffer());
        //to avoid ThreadAbortion
        Response.Flush();
        Response.SuppressContent = true;
        HttpContext.Current.ApplicationInstance.CompleteRequest();
        Response.Close();
    }

.NET - 使用“Response.BinaryWrite()”使IE11关闭

好的,我设法通过在文件名中添加 +".xls" 来解决损坏的 excel 下载。为什么IE而不是Chrome和Firefox要求您在文件名字符串中显式定义扩展名,我永远不会知道。需要明确的是,这并没有解决IE关闭主窗口的问题,但现在这不是问题。