我有一个对象列表,我想通过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为空。所以我猜写流时出了什么问题?
答案 0 :(得分:0)
我认为您需要
return result;
返回“ 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");
现在就像魅力一样工作。摇摇欲坠的输出:
答案 2 :(得分:0)
在ASP.NetCore中,我们有return File(ret, "application/octet-stream", fileName);
以我们需要的类型返回文件,对于我使用"application/octet-stream"
的.msi包,您可以在此处在控制器级别或在{的全局级别中将返回类型指定为.CSV WebApiConfig
的{1}}类