如何在ImageSharp.Web中用IRequestParser重定向Azure容器图片请求
自定义IRequestParser实现ImageSharp.Web路径映射到Azure容器指定目录
需求说明
将https://example.com/directory1/12345/image.jpg的请求,映射到Azure存储容器内的/files/directory1/12345/image.jpg路径。
实现步骤
1. 创建自定义请求解析器
实现IRequestParser接口,修改请求路径以匹配Azure容器内的目标目录结构:
using Microsoft.AspNetCore.Http; using SixLabors.ImageSharp.Web; using SixLabors.ImageSharp.Web.Commands; namespace ImageSharpTest { public class CustomAzurePathRequestParser : IRequestParser { public Task<ImageCommandContext> ParseRequestAsync(HttpContext context) { // 获取原始请求路径(移除开头的斜杠) string originalPath = context.Request.Path.Value?.TrimStart('/') ?? string.Empty; // 为路径添加Azure容器内的目标前缀"/files" string mappedPath = $"files/{originalPath}"; // 更新请求路径 context.Request.Path = $"/{mappedPath}"; // 复用默认解析器处理图片命令参数(如裁剪、格式转换等) var defaultParser = new QueryCollectionRequestParser(); return defaultParser.ParseRequestAsync(context); } } }
2. 替换默认请求解析器
在Program.cs的ImageSharp配置中,将默认的QueryCollectionRequestParser替换为自定义解析器:
services.AddImageSharp() .ClearProviders() // 替换为自定义请求解析器 .SetRequestParser<CustomAzurePathRequestParser>() .Configure<PhysicalFileSystemCacheOptions>(options => { options.CacheRootPath = null; options.CacheFolder = "is-cache"; options.CacheFolderDepth = 8; }) .SetCache<PhysicalFileSystemCache>() .SetCacheKey<UriRelativeLowerInvariantCacheKey>() .SetCacheHash<SHA256CacheHash>() .Configure<PhysicalFileSystemProviderOptions>(options => options.ProviderRootPath = null) .Configure<AzureBlobStorageImageProviderOptions>(options => { options.BlobContainers.Add(new AzureBlobContainerClientOptions { ConnectionString = "DefaultEndpointsProtocol=https;AccountName=ACCOUNT_NAME;AccountKey=ACCOUNT_KEY;EndpointSuffix=core.windows.net", ContainerName = "files" }); }) .AddProvider<AzureBlobStorageImageProvider>() .AddProvider<PhysicalFileSystemProvider>() .AddProcessor<ResizeWebProcessor>() .AddProcessor<FormatWebProcessor>() .AddProcessor<BackgroundColorWebProcessor>() .AddProcessor<QualityWebProcessor>() .AddProcessor<AutoOrientWebProcessor>();
关键说明
- 自定义解析器通过修改
HttpContext.Request.Path,将前端请求路径转换为Azure容器内的实际文件路径。 - 保留默认解析器的逻辑,确保图片处理命令(如
?width=300&format=webp)正常生效。 - 若需更复杂的路径规则,可在
ParseRequestAsync方法中扩展逻辑(如多前缀映射、路径重写等)。
内容的提问来源于stack exchange,提问作者Eyeball
相关产品推荐
相关产品推荐

