Asp.net-Mvc

使用響應流的 MVC 控制器

  • May 20, 2020

我正在使用 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");

我想我可以建構一個字元串,但由於這些文件可能有幾千行長,這對我來說似乎效率低下。

有人能指出我正確的方向嗎?謝謝。

昨天我在類似的問題上花了一些時間,以下是正確的方法:

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

我找到了解決這個問題的一種可能的方法。您可以簡單地定義操作方法以返回 EmptyResult() 並直接寫入響應流。例如:

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

這似乎沒有任何問題。不知道它是如何’MVC’……

引用自:https://stackoverflow.com/questions/7163448