ASP.NET MVC FileResult 正在损坏文件 [英] ASP.NET MVC FileResult is corrupting files

查看:24
本文介绍了ASP.NET MVC FileResult 正在损坏文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试让我的 ASP.NET MVC 网站将一些数据导出为 Excel 文件.几个小时以来,我认为 NPOI 只是在生产垃圾,所以我切换到了 EPPlus.我在 LINQPad 中对其进行了测试,它创建了一个正常工作的 XLSX 文件,因此我将代码移至 MVC 应用程序.再次,我得到损坏的文件.我碰巧查看了临时目录,发现 EPPlus 创建的文件为 3.87KB 并且运行良好,但是 FileResult 返回了一个 6.42KB 的文件,该文件已损坏.为什么会这样?我在某处读到它是由服务器 GZip 压缩引起的,所以我将其关闭,但没有任何效果.有人,请帮助我,我快疯了......这是我的代码.

I've been trying to get my ASP.NET MVC website to export some data as an Excel file. For hours I thought that NPOI was just producing garbage so I switched over to EPPlus. I tested it in LINQPad and it created a proper working XLSX file, so I moved the code over to the MVC app. AGAIN, I get corrupted files. By chance I happened to look at the temp directory and saw that the file created by EPPlus is 3.87KB and works perfectly, but the FileResult is returning a file that's 6.42KB, which is corrupted. Why is this happening? I read somewhere that it was the server GZip compression causing it, so I turned it off, and it had no effect. Someone, please help me, I'm going out of my mind... Here's my code.

[HttpGet]
public FileResult Excel(
    CenturyLinkOrderExcelQueryModel query) {
    var file = Manager.GetExcelFile(query); // FileInfo

    return File(file.FullName, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", query.FileName);
}

推荐答案

就我而言,FileResult 及其附带的方法存在问题.我最终通过覆盖 Response 对象来解决"这个问题:

As far as I'm concerned there's an issue with the FileResult and it's accompanying methods. I ended up "resolving" the issue by overriding the Response object:

[HttpGet]
public void Excel(
    CenturyLinkOrderExcelQueryModel query) {
    var file = Manager.GetExcelFile(query);

    Response.Clear();
    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    Response.AddHeader("Content-Disposition", "attachment; filename=" + query.FileName);
    Response.BinaryWrite(System.IO.File.ReadAllBytes(file.FullName));
    Response.Flush();
    Response.Close();
    Response.End();
}

这篇关于ASP.NET MVC FileResult 正在损坏文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆