无法从 Web 获取文件 api

Cannot get file from web api

我正在尝试通过获取请求发送文件,但此代码无效。我正在使用 .NET Core 并使用 Postman 测试 API。

// POST api/values
[HttpGet]
public HttpResponseMessage Get(string filename)
{
    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
    var stream = new FileStream($"Scans/{filename}.obj", FileMode.Open, FileAccess.Read);
    result.Content = new StreamContent(stream);
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
    return result;
}

当我通过邮递员测试请求时,我得到这个而不是我的流:

{
"version": {
"major": 1,
"minor": 1,
"build": -1,
"revision": -1,
"majorRevision": -1,
"minorRevision": -1
},
"content": {
"headers": [
  {
    "key": "Content-Type",
    "value": [
      "application/octet-stream"
    ]
  },
  {
    "key": "Content-Length",
    "value": [
      "8785871"
    ]
  }
]
},
"statusCode": 200,
"reasonPhrase": "OK",
"headers": [],
"requestMessage": null,
"isSuccessStatusCode": true
}

所以,很奇怪我的代码不起作用,但这里有一些工作代码。 HTTPResponseMessage 似乎无法发送文件。相反,您必须 return 一个 FileResult 对象。

    [HttpGet]
    public FileResult Get(string filename)
    {

        string path = $"Scans/{filename}.obj";

        FileContentResult result = new FileContentResult(System.IO.File.ReadAllBytes(path), "application/octet-stream")
        {
            FileDownloadName = path
        };
        return result;


    }

HttpResponseMessage 来自上一版本的框架。您必须使用 IActionResult 实现 class.

您可以通过控制器return 文件流结果。

[HttpGet]
public IActionResult Get(string filename) {
    var path = $"Scans/{filename}.obj";
    var stream = new FileStream(path, FileMode.Open, FileAccess.Read);
    var response = File(stream, "application/octet-stream"); // FileStreamResult
    return response;
}