MVC控制器使用响应流 [英] MVC Controller Using Response Stream
问题描述
我使用MVC 3,我想动态创建一个CSV文件下载,但我不能确定正确的MVC至上的方针。
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.
在传统的ASP.net,我会写这样的:
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();
我已经看了看ContentResult类型行动,但看来我需要创建的结果作为一个字符串,即
I have looked at the ContentResult action but it appears that I would need to create the result as a string, i.e.
返回内容(MYDATA的,文/ CSV);
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.
推荐答案
我昨天花了类似的问题了一段时间,这里是如何做到这一点正确的方式:
I spent some time on the similar problem yesterday, and here's how to do it right way:
public ActionResult CreateReport()
{
var reportData = MyGetDataFunction();
var serverPipe = new AnonymousPipeServerStream(PipeDirection.Out);
Task.Run(() =>
{
using (serverPipe)
{
MyWriteDataToFile(reportData, serverPipe)
}
});
var clientPipe = new AnonymousPipeClientStream(PipeDirection.In,
serverPipe.ClientSafePipeHandle);
return new FileStreamResult(clientPipe, "text/csv");
}
这篇关于MVC控制器使用响应流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!