asp.net-mvc 使用响应流的 MVC 控制器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7163448/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:25:56  来源:igfitidea点击:

MVC Controller Using Response Stream

asp.net-mvcasp.net-mvc-3actionresult

提问by Neilski

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.

我正在使用 MVC 3 我想动态创建一个 CSV 文件以供下载,但我不确定正确的面向 MVC 的方法。

In conventional ASP.net, I would have written something like:

在传统的 ASP.net 中,我会这样写:

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 ContentResultaction but it appears that I would need to create the result as a string, i.e.

我已经查看了ContentResult操作,但似乎我需要将结果创建为字符串,即

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.

有人能指出我正确的方向吗?谢谢。

采纳答案by galets

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");
}

回答by Neilski

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:

我找到了解决此问题的一种可能方法。您可以简单地定义操作方法来返回一个 EmptyResult() 并直接写入响应流。例如:

public ActionResult RobotsText() {
    Response.ContentType = "text/plain";
    Response.Write("User-agent: *\r\nAllow: /");
    return new EmptyResult();
}

This seems to work without any problems. Not sure how 'MVC' it is...

这似乎没有任何问题。不确定它是如何“MVC”的......

回答by cedd

Try something like this:

尝试这样的事情:

public ActionResult CreateReport(string report, string writer)
{
    var stream = new MemoryStream();
    var streamWriter = new StreamWriter(stream);

    _generateReport.GenerateReport(report, writer);

    streamWriter.Flush();
    stream.Seek(0, SeekOrigin.Begin);

    return new FileStreamResult(stream, writer.MimeType);
}