I need to return an image with a Web API Get method. The code below seems to work fine except that I get this message in the Fiddler's ImageView window, "This response is encoded, but does not claim to be an image."
public HttpResponseMessage Get()
{
using (FileStream fs = new FileStream(filePath, FileMode.Open))
{
HttpResponseMessage response = new HttpResponseMessage();
response.Content = new StreamContent(fs);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
return response;
}
}
I see the same result in the Fiddler with this code also:
public HttpResponseMessage Get()
{
HttpResponseMessage response = new HttpResponseMessage();
Byte[] b = (GetImageByteArray());
response.Content = new ByteArrayContent(b);
response.Content.LoadIntoBufferAsync(b.Length).Wait();
response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
return response;
}
I get the same result if I use .png format.
Appreciate your help,
If I understand correctly then you are asking specific to asp.net core. In ASP.net core HttpResponseMessage is not a way to return result the way we used to do in ASP.net web api 2.
In asp.net core ( WEB API ) simply look like this.
Note: As you mention that in Fiddler Imageview you see message like this "his response is encoded, but does not claim to be an image." because ASP.net core consider HttpResponseMessage as simple class and convert into json or xml.
This is the way I get image from API in my project. I share for whom concern.
Image content save to Images folder in server and image name saved to Database.
Get image content in Angular
In addition to previous answers, use this to get image based on hosting environment within
System.Web.Hosting
namespace.and use
imageUrl
it to findbyte[]
of the image, and process with proper content-type likeimage/jpeg
Adding this answer because those comments are easy to miss (like I nearly did).
Suggested by Jussi Palo (using a PhysicalFileResult):
Suggested by Tseng (using an overload of the FileContentResult constructor that accepts a stream):
For RL remember to check the file/resource exists, and return 404 if not.