FileHelper阅读以流式传输并通过Web API下载

时间:2019-04-25 13:56:02

标签: c# asp.net-web-api filehelpers

我有一个对象列表,我想通过Web Api下载为csv文件。 但是,当我用Swagger测试时,没有CSV下载。 我究竟做错了什么? DailyReportContent包含2个对象。

到目前为止,这是我的代码:

public IActionResult GetDailyReport(DateTime invoiceDate)
{
    var dailyReportContent = new List<DailyReportModel>().....

    // create csv file
    var engine = new FileHelperEngine<DailyReportModel>
    {
        HeaderText = "headers.."
    };

    using (var stream = new MemoryStream())
    using (var streamWriter = new StreamWriter(stream))
    {
        engine.WriteStream(streamWriter, dailyReportContent);

        var result = new HttpResponseMessage(HttpStatusCode.OK);
        result.Content = new StreamContent(stream);
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("text/csv");
        result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "DailyReports.csv" };

        return Ok(result);
    }
}

这是Swagger的响应:

{
  "version": {
    "major": 1,
    "minor": 1,
    "build": -1,
    "revision": -1,
    "majorRevision": -1,
    "minorRevision": -1
  },
  "content": {
    "headers": [
      {
        "key": "Content-Type",
        "value": [
          "text/csv"
        ]
      },
      {
        "key": "Content-Disposition",
        "value": [
          "attachment; filename=DailyReports.csv"
        ]
      }
    ]
  },
  "statusCode": 200,
  "reasonPhrase": "OK",
  "headers": [],
  "requestMessage": null,
  "isSuccessStatusCode": true
}

编辑:即使我添加了此内容:

 stream.Flush();
 streamWriter.Flush();

 var reader = new StreamReader(stream);
 var readResult = reader.ReadToEnd();

readResult为空。所以我猜写流时出了什么问题?

3 个答案:

答案 0 :(得分:0)

我认为您需要

return result;

返回“ Ok()”将返回包含该对象的响应消息。
您已经创建了响应消息并指定了所有内容。
因此,我认为您正在返回一个OK响应,其中包含另一个OK响应消息。

答案 1 :(得分:0)

像这样解决它:

var csvContent = LoadcsvContent();

var engine = new FileHelperEngine<DailyReportModel>
{
    HeaderText = "......."
};

var stream = new MemoryStream();
TextWriter streamWriter = new StreamWriter(stream);
engine.WriteStream(streamWriter, csvContent);

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

return File(await stream, "text/csv", $"Report_{invoiceDate:yyyyMMdd}.csv");

现在就像魅力一样工作。摇摇欲坠的输出:

enter image description here

答案 2 :(得分:0)

在ASP.NetCore中,我们有return File(ret, "application/octet-stream", fileName);

以我们需要的类型返回文件,对于我使用"application/octet-stream"的.msi包,您可以在此处在控制器级别或在{的全局级别中将返回类型指定为.CSV WebApiConfig的{​​1}}类