.NET 6中从中间件调用控制器操作方法及旧代码失效问题
.NET 6迁移后HttpRequest路径重写失效的修复
问题背景
原基于.NET Core 2.2开发的文件下载路径重写代码,迁移到.NET 6后无法触发目标下载方法。原代码如下:
public static void ProcessFileStorageRequest(this HttpRequest request, string path) { path = path.TrimEnd(new[] { '/' }); request.Path = "/productfile/download"; string encodedPath = UrlEncoder.Default.Encode(path); request.QueryString = new QueryString($"?path={encodedPath}"); }
实际现象:请求URL从https://localhost:5000/path/download.html变为https://localhost:5000/path/file.exe/?path=path%2Ffile.exe,预期的/productfile/download路由对应的下载方法未被调用。
原因分析
.NET 6对HttpRequest的Path和QueryString处理逻辑进行了调整:
- 直接赋值
Path时,若未重置PathBase,路由系统可能仍基于原请求的路径前缀解析,导致目标路由匹配失败 - 手动拼接
QueryString时,可能因编码逻辑变化出现重复编码或参数格式错误,影响路由参数识别
修复方案
调整路径重写逻辑,适配.NET 6的路由规则:
public static void ProcessFileStorageRequest(this HttpRequest request, string path) { path = path.TrimEnd('/'); // 重置PathBase,确保路由解析基于完整目标路径 request.PathBase = PathString.Empty; // 设置目标路由路径 request.Path = "/productfile/download"; // 使用官方API安全构建查询字符串,自动处理编码 request.QueryString = QueryString.Create(new Dictionary<string, string> { { "path", path } }); }
关键说明
- .NET 6中
PathBase用于存储请求的路径前缀,修改Path前需重置PathBase,避免路由解析混淆 QueryString.Create方法会自动完成URL编码,无需手动调用UrlEncoder,避免编码错误
内容的提问来源于stack exchange,提问作者lucianobonde
相关产品推荐
相关产品推荐

