使用响应流的 MVC 控制器
我正在使用 MVC 3,我想动态创建一个 CSV 文件以供下载,但我不确定正确的面向 MVC 的方法。
在传统的 ASP.net 中,我会编写如下内容:
Response.ClearHeaders();
Response.ContentType = "text/csv";
Response.AddHeader("content-disposition", attachment;filename='Test.csv'");
Response.Write("1,2,3");
Response.End();
我已经查看了 ContentResult
操作,但看来我需要将结果创建为字符串,即
return Content(myData, "text/csv");
我想,我可以构建一个字符串,但由于这些文件可能有几千行长,这对我来说似乎效率低下。
有人能指出我正确的方向吗?谢谢。
I'm using MVC 3 I would like to dynamically create a CSV file for download, but I am unsure as to the correct MVC orientated approach.
In conventional ASP.net, I would have written something like:
Response.ClearHeaders();
Response.ContentType = "text/csv";
Response.AddHeader("content-disposition", attachment;filename='Test.csv'");
Response.Write("1,2,3");
Response.End();
I have looked at the ContentResult
action but it appears that I would need to create the result as a string, i.e.
return Content(myData, "text/csv");
I could, I suppose, build a string, but since these files could be several thousand lines long, this seems inefficient to me.
Could someone point me in the right direction? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我找到了解决这个问题的一个可能的方法。您可以简单地定义操作方法来返回 EmptyResult() 并直接写入响应流。例如:
这似乎工作没有任何问题。不知道它是如何“MVC”......
I have found one possible solution to this problem. You can simply define the action method to return an EmptyResult() and write directly to the response stream. For example:
This seems to work without any problems. Not sure how 'MVC' it is...
我昨天花了一些时间来解决类似的问题,以下是正确的解决方法:
I spent some time on the similar problem yesterday, and here's how to do it right way:
尝试返回一个
FileResult
:http://msdn.microsoft.com/en-us/library/system.web.mvc.fileresult.aspx另请参阅此示例:http://forums.asp.net/t/1491579.aspx/1
Try returning one the
FileResult
s: http://msdn.microsoft.com/en-us/library/system.web.mvc.fileresult.aspxAlso see this example: http://forums.asp.net/t/1491579.aspx/1
尝试这样的事情:
Try something like this: