【问题标题】:AspNetCore Mvc always returns a JSON objectAspNetCore Mvc 总是返回一个 JSON 对象
【发布时间】:2019-03-19 19:57:17
【问题描述】:

我在 Asp Net Core 中遇到了问题。

我不能将文件作为 blob 数据返回,但不能作为带有编码内容的 JSON 对象返回到 base64。

这是我的 C# 代码:

[Route("DownloadExcel")]
[HttpPost]
public async Task<FileContentResult> DownloadExcel([FromBody] Queries.In.Pages.Users.ExportToExcel.InModel model)
{
    //some logic to retrieve an array of bytes.
    var filename = $"myFile_{DateTime.Now:yyyyMMdd_hh_mm}.xlsx";
    return File(byteArray, "octet/stream", filename);
}

在 Angular 6 侧:

this.httpClient.post(url, model, {headers: headers, responseType: 'blob'} )
  .subscribe(res => {
       let blob = new Blob(["\ufeff", response], {type: 'octet/stream'});
       saveAs(blob, '111.xlsx');
   })

我在浏览器响应选项卡中看到的结果是什么? 和标题:

我的项目有什么问题以及如何修改它以检索 blob 而不是 JSON?

提前致谢!

【问题讨论】:

  • 您为什么使用octet/stream MIME 类型而不是正确的excel 类型application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
  • 请试试这个stackoverflow.com/questions/41984491/…改变逻辑accodingly
  • 我觉得应该是IActionResult返回类型的Task。

标签: c# angular asp.net-core blob angular6


【解决方案1】:

在 ASP.NET Core 中,如果要发送自定义响应,则需要使用 IActionResult。所有其他响应将被序列化(默认为 JSON)并作为响应正文发送。

参考File Streaming in ASP.NET Core的答案

【讨论】:

    猜你喜欢
    • 2013-12-29
    • 2015-09-05
    • 1970-01-01
    • 2013-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-12
    相关资源
    最近更新 更多