Asp.net

HttpResponseMessage 不返回 ByteArrayContent - ASP.NET Core

  • March 17, 2017

我將文件儲存在數據庫中,需要 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 呼叫返回的,因為我明確添加了它。

我認為您應該使用 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");
}

引用自:https://stackoverflow.com/questions/42862627