I have a Restful ASP.NET Web API 2 with the following method that returns a HttpResponseMessage with an image as content:
[AllowAnonymous]
[HttpGet, Route("{id}/image/"]
public HttpResponseMessage GetImage(int id)
{
try
{
var artwork = Service.GetSingle(id);
if(!isValidArtwork(artwork)) {
Request.CreateResponse(HttpStatusCode.NotFound);
}
string mediaHeaderValue;
switch (Path.GetExtension(artwork.filePath))
{
case ".jpg":
mediaHeaderValue = "image/jpg";
break;
case ".jpeg":
mediaHeaderValue = "image/jpg";
break;
case ".bmp":
mediaHeaderValue = "image/jpg";
break;
case ".png":
mediaHeaderValue = "image/png";
break;
default:
return new HttpResponseMessage(HttpStatusCode.NotFound);
}
using(var fileStream = File.Open(artwork.filePath, FileMode.Open, FileAccess.Read)){
var response = new HttpResponseMessage { Content = new StreamContent(fileStream) };
response.Content.Headers.ContentType = new MediaTypeHeaderValue(mediaHeaderValue);
response.Content.Headers.ContentLength = fileStream.Length;
return response;
}
}
catch (Exception){
return Request.CreateResponse(HttpStatusCode.NotFound);
}
}
The method is working as intended in Chrome/Opera/Mozilla but in Internet Explorer (version 10/11), the following error is thrown: "The process cannot access the file because it is being used by another process".
I've tried different ways of closing/disposing the stream, using different file access attributes and setting the content as a byte array. However, the same error appears when using Internet Explorer (version 10/11).
Any suggestions on how this can be resolved? Or had similar problems with Internet Explorer (version 10/11)?
It is weird that this behaviour only triggers when the request is made from Internet Explorer. However, I've managed to find a solution. I was missing the FileShare.Read attribute when opening the file.
var fileStream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
I've found another solution too. Copying the image data to a byte array, and disposing the file stream. Then use the byte array as content of the response message.