Kentico多个媒体库关联不同Azure存储容器配置失效问题
多Azure存储容器媒体库映射失效修复
问题现象
需求为创建2个独立媒体库,分别关联2个不同的Azure存储容器。使用代码配置后规则不生效:所有文件无论上传到哪个媒体库,最终都会存储到ConfigurationManager.AppSettings["CMSAzureContainerName"]指定的默认容器中。
原实现代码:
string[] subDirectories = new string[] { "cms", "memberdocuments" }; if (subDirectories != null) { for (int i = 0; i < subDirectories.Length; i++) { if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["CMSAzureMemberDocsContainerName"]) && subDirectories[i].ToLower().Contains("memberdocuments")) { var mediaProvider = StorageProvider.CreateAzureStorageProvider(); mediaProvider.CustomRootPath = ConfigurationManager.AppSettings["CMSAzureMemberDocsContainerName"]; mediaProvider.PublicExternalFolderObject = false; StorageHelper.MapStoragePath("~/rthealth", mediaProvider); } else if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["CMSAzureAccountName"])) { var mediaProvider = StorageProvider.CreateAzureStorageProvider(); mediaProvider.CustomRootPath = ConfigurationManager.AppSettings["CMSAzureContainerName"]; mediaProvider.PublicExternalFolderObject = false; StorageHelper.MapStoragePath("~/rthealth", mediaProvider); } } }
根因分析
- 两次调用
StorageHelper.MapStoragePath绑定的虚拟路径完全一致,均为~/rthealth,后注册的存储提供程序会直接覆盖前序规则,循环执行完后最终只剩默认容器的配置生效 - 循环逻辑未将子目录名称拼接至映射虚拟路径,框架无法根据上传文件的所属路径,判断应该路由到哪个存储容器
- 分支判断逻辑粗糙,只要路径不匹配
memberdocuments关键词就全部走默认容器,未做精确路径匹配
修复代码
// 统一提前读取配置,减少重复判断 string defaultCmsContainer = ConfigurationManager.AppSettings["CMSAzureContainerName"]; string memberDocsContainer = ConfigurationManager.AppSettings["CMSAzureMemberDocsContainerName"]; string azureAccountName = ConfigurationManager.AppSettings["CMSAzureAccountName"]; if (!string.IsNullOrEmpty(azureAccountName)) { // 注册CMS默认媒体库存储提供程序,精确绑定到对应子路径 var cmsStorageProvider = StorageProvider.CreateAzureStorageProvider(); cmsStorageProvider.CustomRootPath = defaultCmsContainer; cmsStorageProvider.PublicExternalFolderObject = false; StorageHelper.MapStoragePath("~/rthealth/cms", cmsStorageProvider); // 成员文档容器配置合法时,注册专属存储提供程序 if (!string.IsNullOrEmpty(memberDocsContainer)) { var memberDocStorageProvider = StorageProvider.CreateAzureStorageProvider(); memberDocStorageProvider.CustomRootPath = memberDocsContainer; memberDocStorageProvider.PublicExternalFolderObject = false; StorageHelper.MapStoragePath("~/rthealth/memberdocuments", memberDocStorageProvider); } // 可选:根路径默认路由到CMS容器,需放在子路径映射之后注册 var rootProvider = StorageProvider.CreateAzureStorageProvider(); rootProvider.CustomRootPath = defaultCmsContainer; rootProvider.PublicExternalFolderObject = false; StorageHelper.MapStoragePath("~/rthealth", rootProvider); }
配置注意事项
- 创建两个媒体库时,需分别将根路径指定为
~/rthealth/cms和~/rthealth/memberdocuments,不能直接使用上层~/rthealth作为媒体库根目录,否则会命中根路径默认路由规则,所有文件都会存入默认容器 - 存储提供程序注册逻辑建议放在应用启动阶段执行,不要放在接口请求、页面加载这类动态执行的逻辑中重复注册,避免出现路径映射被意外覆盖的问题
- 如果两个媒体库使用同一个Azure存储账号,不需要单独为成员文档容器配置账号名、访问密钥,仅需配置不同的容器名称即可
内容的提问来源于stack exchange,提问作者chamara
相关产品推荐
相关产品推荐

