Rob*_*Coy 3 asp.net asp.net-mvc asp.net-core asp.net-core-webapi
我将文件存储在数据库中,需要Web API才能返回。数据库调用正确地返回了正确的字节数组(Breakpoint显示该数组的长度约为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;
}
Run Code Online (Sandbox Code Playgroud)
我得到的典型响应(在任何地方都找不到字节内容):
{
"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
}
Run Code Online (Sandbox Code Playgroud)
也许我在误解我应该如何处理这些数据,但是我觉得应该从Web API调用中返回该值,因为我已明确添加它。
我认为您应该使用FileContentResult,并且可能使用比“ application / octet-stream”更具体的内容类型
public IActionResult GetFile(int id)
{
var fileToDownload = getFileFromDatabase(id);
if (fileToDownload == null)
{
return NotFound();
}
return new FileContentResult(fileToDownload.FileData, "application/octet-stream");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3193 次 |
| 最近记录: |