Search code examples
c#.netwindows-phone.net-4.5ashx

Read ashx jpg with .Net 4.5


My goal is to read a jpg file from a ashx Url. I would like to do this with Windows Phone 8 but I'm starting with .Net 4.5 because that might be more simple for me.

Here is an example url: http://gatherer.wizards.com/Handlers/Image.ashx?multiverseid=239959&type=card

If you go to this Url in IE 10 you'll see an image. How do I download the image in .Net 4.5? I have tried using:

HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("image/jpg"));
string resourceAddress = "http://gatherer.wizards.com/Handlers/Image.ashx?multiverseid=239959&type=card";
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, resourceAddress);

HttpResponseMessage response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseContentRead);

byte[] responseBytes = await response.Content.ReadAsByteArrayAsync();

and also using WebClient

string url = @"http://gatherer.wizards.com/Handlers/Image.ashx?multiverseid=220041&type=card";
byte[] imageData;
using (WebClient client = new WebClient())
{                
    imageData = client.DownloadData(new Uri(url));
}

both of these methods return no data. How do I get the data and format it into a jpg? I am pretty new to using ashx files. I see that they are used easily in Asp.Net web sites but have not been able to find anything that allows to simply download the file. The goal is to download the jpg file and display it in a windows phone 8 application.


Solution

  • Take a look at that URL. You've URL encoded the &, so indeed there's nothing returned from

    http://gatherer.wizards.com/Handlers/Image.ashx?multiverseid=220041&type=card
    

    this

    http://gatherer.wizards.com/Handlers/Image.ashx?multiverseid=220041&type=card
    

    however, worked just fine for me in Windows 8 using your first code sample.

    By the way, I see you set an Accept header of image/jpg, the ASHX seems to set the Content-type to image/jpeg - it does work though.