MVC Controller Using Response Stream

前端 未结 4 564
轮回少年
轮回少年 2020-12-09 12:06

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 wo

相关标签:
4条回答
  • 2020-12-09 12:38

    Try returning one the FileResults: http://msdn.microsoft.com/en-us/library/system.web.mvc.fileresult.aspx

    Also see this example: http://forums.asp.net/t/1491579.aspx/1

    0 讨论(0)
  • 2020-12-09 12:39

    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:

    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...

    0 讨论(0)
  • 2020-12-09 12:42

    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");
    }
    
    0 讨论(0)
  • 2020-12-09 12:46

    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);
    }
    
    0 讨论(0)
提交回复
热议问题