I've been spinning my tires trying to use ASP.NET Web API to return images. I've seen a number of examples, but I keep running into problems.
After searching for a solution, most examples suggest using HttpResponseMessage and setting the Content and Content-Type header correctly. For example in the following posts: WebApi: How to handle Images ASP .Net Web API downloading images as binary
Here's what I am doing now:
[System.Web.Http.HttpGet]
[ActionName("ConvertHTMLToImage")]
public HttpResponseMessage ConvertHTMLToImage(string htmlString)
{
var path = @"C:\temp\mona-lisa.png";
var response = Request.CreateResponse(HttpStatusCode.OK);
var fileStream = new FileStream(path, FileMode.Open, FileAccess.Read);
response.Content = new StreamContent(fileStream);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
return response;
}
I'm getting mixed results. When I go the URL for that resource I have problems with Chrome (This webpage is not available), Firefox (The connection was reset), and Safari (Safari can’t open the page). Much to my surprise, it works fine in IE. I can also successfully view the image using the composer in Fiddler. If I keep Fiddler open and access the resource using Chrome/Firefox/Safari, I see 504 errors. Not sure what the means, I can't remember ever having seen that error type before.
I also noticed some strange behavior in the debugger with the browsers that aren't working. If I call ConvertHTMLToImage from IE and Fiddler, I see it stop at my break-point once and then the image is sucessfully returned to the client. On Chrome/Firefox/Safari there are multiple calls into the method. Sometimes twice sometimes 3 times. I have no explanation for this. I don't get any errors that I can detect other than the browser doesn't show the image.
I've done this same thing using aspx pages, HttpHhandlers, and other .NET methods so I know there are work-arounds, but I really would like to know what I'm doing wrong. This seems like something that should be easily accomplished using the Web API.