public async Task Invoke(HttpContext context) { var path = context.Request.Path; if (!path.StartsWithSegments("/images", System.StringComparison.OrdinalIgnoreCase) && !path.StartsWithSegments("/category/image", System.StringComparison.OrdinalIgnoreCase)) { await _next(context); return; } var fileName = Path.GetFileName(context.Request.Path.Value); var content = await _cacheService.GetAsync(fileName); if (content != null) { var contentType = _mimeHelper.GetMimeType(content); context.Response.ContentType = contentType; await context.Response.Body.WriteAsync(content); return; } var originalBody = context.Response.Body; byte[] responseContent; try { using (var memStream = new MemoryStream()) { context.Response.Body = memStream; await _next(context); memStream.Seek(0, SeekOrigin.Begin); responseContent = memStream.ToArray(); memStream.Seek(0, SeekOrigin.Begin); await memStream.CopyToAsync(originalBody); } } finally { context.Response.Body = originalBody; } if (!string.IsNullOrWhiteSpace(context.Response.ContentType) && context.Response.ContentType.StartsWith("image")) { await _cacheService.AddAsync(fileName, responseContent); } }
public async Task <IActionResult> Image(int id) { var image = await _categoryService.GetCategoryImageAsync(id); if (image == null) { return(NotFound()); } return(File(image, _mimeHelper.GetMimeType(image))); }