【发布时间】:2017-08-09 07:30:06
【问题描述】:
我将文件存储在数据库中,需要 Web API 才能返回。数据库调用正确地返回了正确的字节数组(断点显示数组的长度约为 67000,这是正确的),但是当我调用 Web API 时,我从未在响应中得到该内容。我试过使用 MemoryStream 和 ByteArrayContent,但都没有给我应该得到的结果。我已经尝试从 Postman 和我的 MVC 应用程序调用,但都没有返回字节数组,只返回带有 headers/success/etc 的基本响应信息。
public HttpResponseMessage GetFile(int id)
{
var fileToDownload = getFileFromDatabase(id);
if (fileToDownload == null)
{
return new HttpResponseMessage(HttpStatusCode.BadRequest);
}
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new ByteArrayContent(fileToDownload.FileData); //FileData is just a byte[] property in this class
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return response;
}
我得到的典型响应(在任何地方都找不到字节内容):
{
"version": {
"major": 1,
"minor": 1,
"build": -1,
"revision": -1,
"majorRevision": -1,
"minorRevision": -1
},
"content": {
"headers": [
{
"key": "Content-Disposition",
"value": [
"attachment"
]
},
{
"key": "Content-Type",
"value": [
"application/octet-stream"
]
}
]
},
"statusCode": 200,
"reasonPhrase": "OK",
"headers": [],
"requestMessage": null,
"isSuccessStatusCode": true
}
也许我误解了我应该如何处理这些数据,但我觉得这应该是从 Web API 调用返回的,因为我明确添加了它。
【问题讨论】:
-
您能确保您请求的操作方法正确吗?关于 GetFile 操作方法不会返回您描述的 JSON 结果。
-
Joe 的评论解决了我的问题。我遗漏了文件上方的 Route 属性...调用是正确的,对不起!
标签: asp.net asp.net-mvc asp.net-core asp.net-core-webapi