无法从 web api 获取文件

Ale*_*ios 4 c# postman asp.net-core asp.net-core-webapi

我正在尝试通过 get 请求发送文件,但此代码不起作用。我正在使用 .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;
}
Run Code Online (Sandbox Code Playgroud)

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

{
"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
}
Run Code Online (Sandbox Code Playgroud)

Nko*_*osi 5

HttpResponseMessage来自之前版本的框架。您必须使用已IActionResult实现的类。

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

[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;
}   
Run Code Online (Sandbox Code Playgroud)