/// <summary>Invoke /// </summary> public async Task Invoke(HttpContext context) { var path = context.Request.Path; // hand to next middleware if we are not dealing with an image if (context.Request.Query.Count == 0 || !IsImagePath(path)) { await _next.Invoke(context); return; } //图片需要的参数 var resizeParameter = GetResizeParameter(context.Request.Query); //无参数,不缩放 if (!resizeParameter.HasParams()) { await _next.Invoke(context); return; } //图片路径 var imagePath = Path.Combine( _env.WebRootPath, path.Value.Replace('/', Path.DirectorySeparatorChar).TrimStart(Path.DirectorySeparatorChar)); //图片不存在 if (!File.Exists(imagePath)) { await _next.Invoke(context); return; } //图片最后修改时间 var lastWriteTimeUtc = File.GetLastWriteTimeUtc(imagePath); //图片二进制 byte[] imageBytes = await _imageResizeService.GetImageData(imagePath, resizeParameter, lastWriteTimeUtc); //无法调整图片,那么就直接返回下一个 if (imageBytes == null || imageBytes.Length <= 0) { await _next.Invoke(context); return; } //contentType context.Response.ContentType = MimeTypeNameUtil.GetMimeName(resizeParameter.Format); context.Response.ContentLength = imageBytes.Length; await context.Response.Body.WriteAsync(imageBytes.ToArray(), 0, imageBytes.Length); }
public void GetMimeName_Test() { var actual = MimeTypeNameUtil.GetMimeName("Xls"); Assert.Equal("application/vnd.ms-excel", actual); }