【问题标题】:How to return and open a file using Web API in C# instead of json response如何在 C# 中使用 Web API 而不是 json 响应返回和打开文件
【发布时间】:2020-05-12 18:47:00
【问题描述】:

我一直在关注下面链接的帖子中的答案,以便使用 dotnet api 返回文件以返回文件。

How to return a file using Web API?

虽然我可以大摇大摆地打电话,但是当我直接导航到 URL 时,我得到的只是一个 json 对象,而不是浏览器打开文件。(https://localhost:5001/api/SiteLink/gandrfiles/1)。

任何想法为什么浏览器不会打开文件?谢谢!

Json 返回:

{
  "version": {
    "major": 1,
    "minor": 1,
    "build": -1,
    "revision": -1,
    "majorRevision": -1,
    "minorRevision": -1
  },
  "content": {
    "headers": [
      {
        "Key": "Content-Disposition",
        "Value": [
          "attachment; filename=Contact_Us_Page.pdf"
        ]
      },
      {
        "Key": "Content-Type",
        "Value": [
          "application/octet-stream"
        ]
      }
    ]
  },
  "statusCode": 200,
  "reasonPhrase": "OK",
  "headers": [],
  "trailingHeaders": [],
  "requestMessage": null,
  "isSuccessStatusCode": true
}

我最终遵循了 Amir Shirazi 提供的原始帖子的答案,并且成功了。我不知道为什么 Regfor 的答案没有起到作用,但它在项目中不起作用。

【问题讨论】:

    标签: c# api file download


    【解决方案1】:

    您可能需要查看从 API 返回的 Content-Type。试试“application/octet-steam”

        result.Content.Headers.ContentType = 
            new MediaTypeHeaderValue("application/octet-stream");
    

    【讨论】:

    • 我修改了我的代码以包含它;但是,按照 Amir Shirazi 在该帖子中提供的答案,我能够让它工作。其他方式,只是打开一个 json 响应但没有文件。感谢您的建议!。
    猜你喜欢
    • 2012-04-08
    • 2021-08-03
    • 2016-02-11
    • 1970-01-01
    • 2020-02-15
    • 1970-01-01
    • 2016-12-20
    • 2020-06-13
    相关资源
    最近更新 更多