Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpResponseMessage not returning ByteArrayContent - ASP.NET Core

I have files stored in a database that I need a Web API to return. The database call correctly returns the proper byte array (Breakpoint shows the array being around 67000 in length, which is correct), but when I make a call to the Web API, I never get that content in the response. I've tried using a MemoryStream and ByteArrayContent, and neither give me the results I should be getting. I've tried calling from both Postman and my MVC application, but neither return the byte array, just the basic response information with 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;
}

Typical Response I get (with no byte content anywhere to be found):

{
  "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
}

Maybe I'm misinterpreting how I should be handling this data, but I feel like this should be getting returned from the Web API call since I explicitly add it.

like image 511
Robert McCoy Avatar asked Mar 17 '17 16:03

Robert McCoy


1 Answers

I think you should use FileContentResult, and probably a more specific content type than "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");
}
like image 90
Joe Audette Avatar answered Sep 30 '22 11:09

Joe Audette