public async Task <IActionResult> GetImageAsync(string filename, [FromServices] IMemoryCache cache) { try { var invalidChars = Path.GetInvalidFileNameChars(); if (filename.IndexOfAny(invalidChars) >= 0) { Logger.LogWarning($"Invalid filename attempt '{filename}'."); return(BadRequest("invalid filename")); } Logger.LogTrace($"Requesting image file {filename}"); if (_cdnSettings.GetImageByCDNRedirect) { var imageUrl = Utils.CombineUrl(_cdnSettings.CDNEndpoint, filename); return(Redirect(imageUrl)); } var imageEntry = await cache.GetOrCreateAsync(filename, async entry => { Logger.LogTrace($"Image file {filename} not on cache, fetching image..."); entry.SlidingExpiration = TimeSpan.FromMinutes(AppSettings.ImageCacheSlidingExpirationMinutes); var imgBytesResponse = await _imageStorageProvider.GetAsync(filename); return(imgBytesResponse); }); if (imageEntry.IsSuccess) { return(File(imageEntry.Item.ImageBytes, imageEntry.Item.ImageContentType)); } Logger.LogError($"Error getting image, filename: {filename}, {imageEntry.Message}"); return(_blogConfig.ContentSettings.UseFriendlyNotFoundImage ? (IActionResult)File("~/images/image-not-found.png", "image/png") : NotFound()); } catch (Exception e) { Logger.LogError(e, $"Error requesting image {filename}"); return(ServerError()); } }
public async Task <IActionResult> GetImageAsync(string filename) { try { var invalidChars = Path.GetInvalidFileNameChars(); if (filename.IndexOfAny(invalidChars) > 0) { Logger.LogWarning($"Invalid filename attempt '{filename}'."); return(BadRequest("invalid filename")); } Logger.LogTrace($"Requesting image file {filename}"); var imageEntry = await Cache.GetOrCreateAsync(filename, async entry => { Logger.LogTrace($"Image file {filename} not on cache, fetching image..."); entry.SlidingExpiration = TimeSpan.FromMinutes(AppSettings.ImageCacheSlidingExpirationMinutes); var imgBytesResponse = await _imageStorageProvider.GetAsync(filename); return(imgBytesResponse); }); if (imageEntry.IsSuccess) { return(File(imageEntry.Item.ImageBytes, imageEntry.Item.ImageContentType)); } Logger.LogError($"Error getting image, filename: {filename}, {imageEntry.Message}"); return(AppSettings.UsePictureInsteadOfNotFoundResult ? (IActionResult)File("~/images/image-not-found.png", "image/png") : NotFound()); } catch (Exception e) { Logger.LogError(e, $"Error requesting image {filename}"); return(ServerError()); } }