【问题标题】:Cannot get file from web api无法从 web api 获取文件
【发布时间】:2017-09-19 04:09:54
【问题描述】:

我正在尝试通过获取请求发送文件,但此代码不起作用。我正在使用 .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
}

【问题讨论】:

标签: c# asp.net-core postman asp.net-core-webapi


【解决方案1】:

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;
}   

【讨论】:

    【解决方案2】:

    所以,很奇怪我的代码没有工作,但这里有一些工作代码。看来 HTTPResponseMessage 无法发送文件。相反,您必须返回一个 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;
    
    
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-26
      • 2015-09-27
      • 1970-01-01
      • 1970-01-01
      • 2018-12-20
      • 2015-12-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多