Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refit (C#) - Downloading image

Tags:

c#

refit

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

like image 333
Chris Avatar asked Feb 09 '17 15:02

Chris


2 Answers

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();
like image 200
hyperspasm Avatar answered Oct 21 '22 01:10

hyperspasm


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();
like image 4
Mina Jacob Avatar answered Oct 21 '22 02:10

Mina Jacob