连运港网络公司做网站,软件外包公司好不好,百度营销官网,建筑设计专业推荐网站前言上次#xff0c;我们实现了根据 subpath 特定格式《动态设置静态文件存储目录》。例如#xff1a;subpath静态文件路径/userAId/1.jpgc:\abc\userAId\1.jpg/userBId/1.jpgd:\xyz\123\userBId\1.jpg但是#xff0c;如果 subpath 不能有这种特定格式#xff0c;只能用通用…前言上次我们实现了根据 subpath 特定格式《动态设置静态文件存储目录》。例如subpath静态文件路径/userAId/1.jpgc:\abc\userAId\1.jpg/userBId/1.jpgd:\xyz\123\userBId\1.jpg但是如果 subpath 不能有这种特定格式只能用通用格式比如https://hostname/StaticFiles/images/1.jpg。怎么实现思路请求上下文肯定包含了信息能够区分出用户比如 Session/Cookie、二级域名等可以通过它来反向映射出静态文件路径。例如二级域名静态文件路径a.mycompany.comc:\abc\b.mycompany.comd:\xyz\123在 IFileProvider 接口实现中我们获取不到当前请求上下文但是中间件可以。查看 UseStaticFiles 源代码它使用的是 StaticFileMiddleware 中间件:public static IApplicationBuilder UseStaticFiles(this IApplicationBuilder app, StaticFileOptions options)
{...return app.UseMiddlewareStaticFileMiddleware(Options.Create(options));
}查看 StaticFileMiddleware 源代码[1]它的关键实现是这个TryServeStaticFile 方法public class StaticFileMiddleware
{...private Task TryServeStaticFile(HttpContext context, string? contentType, PathString subPath){var fileContext new StaticFileContext(context, _options, _logger,
_fileProvider, contentType, subPath);if (!fileContext.LookupFileInfo()){_logger.FileNotFound(fileContext.SubPath);}else{// If we get here, we can try to serve the filereturn fileContext.ServeStaticFile(context, _next);}return _next(context);}
}具体如何获取静态文件是依赖_fileProvider因此我们只需要替换 _fileProvider换成根据请求上下文获取对应 PhysicalFileProvider 的方法即可。实现创建 MyIOStaticFileMiddleware复制 StaticFileMiddleware 的原始代码仅仅修改 TryServeStaticFile 方法public class MyIOStaticFileMiddleware
{...private Task TryServeStaticFile(HttpContext context, string? contentType, PathString subPath){var fileContext new StaticFileContext(context, _options, _logger,
GetPhysicalFileProvider(context), contentType, subPath);...return _next(context);}
}然后根据 context 获取对应的 PhysicalFileProvider 进行处理private IFileProvider GetPhysicalFileProvider(HttpContext context)
{//实际可从数据库获取if (context.Request.Host.Host.StartsWith(a.mycompany.com)){return new PhysicalFileProvider(c:\abc);}if (context.Request.Host.Host.StartsWith(b.mycompany.com)){return new PhysicalFileProvider(d:\xyz\123);}...
}使用按如下方式配置静态文件中间件app.UseMiddlewareMyIOStaticFileMiddleware();运行效果如图结论今天我们通过自定义 StaticFileMiddleware实现了根据请求上下文动态设置静态文件存储目录。想了解更多内容请关注我的个人公众号”My IO“参考资料[1]源代码: https://github.com/dotnet/aspnetcore/blob/main/src/Middleware/StaticFiles/src/StaticFileMiddleware.cs