How to to return an image with Web API Get method
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.
[Route("api/dashboard/GetImage")]
public byte[] GetImage(int componentId)
{
using (var dashboardService = new DashboardService())
{
var component = dashboardService.GetImage(componentId);
var context = HttpContext.Current;
string filePath = context.Server.MapPath("~/Images/" + component.ImageName);
context.Response.ContentType = "image/jpeg";
using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
{
using (var memoryStream = new MemoryStream())
{
fileStream.CopyTo(memoryStream);
Bitmap image = new Bitmap(1, 1);
image.Save(memoryStream, ImageFormat.Jpeg);
byte[] byteImage = memoryStream.ToArray();
return byteImage;
}
}
}
}
Get image content in Angular
this.dashboardService.getImage(this.componentId)
.subscribe((blob: any) => {
let objectURL = 'data:image/jpeg;base64,' + blob;
this.imageUrl = this.sanitizer.bypassSecurityTrustUrl(objectURL);;
});
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.
[HttpGet]
public IActionResult Get()
{
Byte[] b = System.IO.File.ReadAllBytes(@"E:\\Test.jpg"); // You can use your own method over here.
return File(b, "image/jpeg");
}
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.