14

I'm using Refit in my C# application to interact with a REST API, and the API method has a call that returns a .jpg image. I want to download this image using Refit and get it as a byte array, but it seems to return a garbled string. See below. See below interface method for downloading of the image

 [Get("/Photos/{id}")]
 Task<string> DownloadPhoto(Guid id);

I tried parsing the string as a Base64 string but that didn't work, so I presume it's not that. Any ideas?

EDIT: First line of garbled response here. Note if going to this same URL in a browser it works fine and displays the image

����\0\u0010JFIF\0\u0001\u0001\0\0H\0H\0\0��\0XExif\0\0MM\0*\0\0\0\b\0\u0002\u0001\u0012\0\u0003\0\0\0\u0001\0\u0001\0\0�i\0\u0004\0\0\0\u0001\0\0\0&\0\0\0\0\0\u0003�\u0001\0\u0003\0\0\0\u0001\0\u0001\0\0�\u0002\0\u0004\0\0\0\u0001\0\0\u0002X�\u0003\0\u0004\0\0\0\u0001\0\0\u0003 \0\0\0\0��\08Photoshop 3.0\08BIM\u0004\u0004\0\0\0\0\0\08BIM\u0004%\0\0\0\0\0\u0010�\u001d�ُ\0�\u0004�\t���B~��\0\u0011\b\u0003 \u0002X\u0003\u0001\"\0\u0002\u0011\u0001\u0003\u0011\u0001��\0\u001f

FabioStein
  • 750
  • 7
  • 23
Chris
  • 7,415
  • 21
  • 98
  • 190

3 Answers3

23

What worked for me was to have the method declared as returning Task<HttpContent> and then you can retrieve the data from the returned HttpContent instance in a variety of manners.

For example:

Task<HttpContent> DownloadPhoto(Guid id);

And then:

HttpContent content = await DownloadPhoto(guid);
byte[] bytes = await content.ReadAsByteArrayAsync();
hyperspasm
  • 1,243
  • 1
  • 16
  • 27
6

you can get the byte array using refit as in the example below

[Get("/Photos/{id}")]
Task<HttpResponseMessage> DownloadPhoto(Guid id);

and then you can get the byte array from

var Response = await YourRefitClient.DownloadPhoto(id);
byte[] ByteArray = await Response.Content.ReadAsByteArrayAsync();
Mina Jacob
  • 1,881
  • 22
  • 23
1

Don't use HttpResponseMessage!

I see everyone using HttpResponseMessage on the internet but this might bring you a hidden problem as it happened to my team when we did it. We all know that for catching Refit errors we shout catch ApiException, but if you call .EnsureSuccessStatusCode() on the response of HttpResponseMessage this will throw a HttpResponseException instead! With that we had some issues where when we had try/catch for ApiException, it was not catching those errors. To simplify your code, avoid it!

Solution:

[Get("/file")]
Task<ApiResponse<Stream>> GetFile();

This way you have access to all common operations:

response.Headers;
response.StatusCode;
await response.EnsureSuccessStatusCodeAsync();
response.Content; <- This is a Stream
FabioStein
  • 750
  • 7
  • 23