The below code is working perfect. It serves the specified image.
public HttpResponseMessage Get(string id)
{
string fileName = string.Format("{0}.png", id);
FileStream fileStream = File.Open(System.Web.Hosting.HostingEnvironment.MapPath("~/Images/" + fileName), FileMode.Open);
HttpResponseMessage response = new HttpResponseMessage { Content = new StreamContent(fileStream) };
response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpg");
response.Content.Headers.ContentLength = fileStream.Length;
return response;
}
Just to release the resource that I acquired to read the image file I have modified the code as follows.
public HttpResponseMessage Get(string id)
{
string fileName = string.Format("{0}.png", id);
using (FileStream fileStream = File.Open(System.Web.Hosting.HostingEnvironment.MapPath("~/Images/" + fileName), FileMode.Open))
{
HttpResponseMessage response = new HttpResponseMessage { Content = new StreamContent(fileStream) };
response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpg");
response.Content.Headers.ContentLength = fileStream.Length;
return response;
}
}
I am getting the error "Error while copying content to a stream". Yes. I am closing the resource before it is streamed.
But the question is how to serve the image and still close the unhandled resource? Asp.Net Web API 2 and above. Thank you for your thoughts.