using GrossesMitainesAPI.Data; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Cors; using Microsoft.AspNetCore.Mvc; namespace GrossesMitainesAPI.Controllers { [EnableCors("_myAllowSpecificOrigins"), ApiController, Route("api/[controller]"), Authorize(AuthenticationSchemes = "Identity.Application")] public class ImageController : ControllerBase { private readonly InventoryContext _context; private readonly IWebHostEnvironment _hostEnvironment; private readonly ILogger _logger; public ImageController(ILogger logger, InventoryContext context, IWebHostEnvironment hostEnvironment) { _context = context; _hostEnvironment = hostEnvironment; _logger = logger; } [EnableCors("_myAllowSpecificOrigins"), HttpGet(Name = "Image"), AllowAnonymous] public IActionResult Get(int id, bool? thumbnail = false) { string path; string filename; string filetype; try { var prod = _context.Products.Where(x => x.Id == id).First(); filename = prod.ImageName ?? throw new Exception("Unable to find product image name. Sending default.jpg instead..."); } catch (Exception e) { _logger.LogError(8, e.Message); filename = "default.jpg"; } path = thumbnail == true ? Path.Combine(_hostEnvironment.ContentRootPath, "Images", Path.GetFileNameWithoutExtension(filename) + "_thumbnail" + Path.GetExtension(filename)) : Path.Combine(_hostEnvironment.ContentRootPath, "Images", filename); if (!System.IO.File.Exists(path)) { _logger.LogError(8, "Unable to find image. Sending default image instead..."); path = Path.Combine(_hostEnvironment.ContentRootPath, "Images", "default.jpg"); } switch (Path.GetExtension(path)) { case ".jpg": case ".jpeg": filetype = "image/jpeg"; break; case ".png": filetype = "image/png"; break; default: filetype = "image/jpeg"; break; } byte[] imageData = System.IO.File.ReadAllBytes(path); return File(imageData, filetype); } } }