我认为这里的一个很好的解决方案是将生产<connectionStrings> 部分输入Web.config 并对其进行加密,然后将加密的<connectionStrings> 部分移动到转换文件(例如Web.Release.config)并对其进行注释以便它在转换时替换整个 <connectionStrings> 部分。这实现了使用同样加密的生产连接字符串部署 Web.config 的目标。
我已按照“在 Windows Azure 中保护您的连接字符串”中的指南,部分 1、2、3 和 4 了解如何加密 Web.config。我建议作为一个完整的参考,其他人也这样做。我将概述我为解决我的场景而执行的主要步骤。
使用生产设置更新 Web.config 中的 <connectionStrings> 部分后,我安装了 Pkcs12 Protected Configuration Provider 并运行 aspnet_regiis.exe 来加密该部分(在 Visual Studio 命令提示符中,位于项目目录中):
aspnet_regiis -pef "connectionStrings" "." -prov "CustomProvider"
我还在 Web.config 中添加了CustomProvider 的定义:
<configProtectedData>
<providers>
<add name="CustomProvider" thumbprint="<your thumbprint here>"
type="Pkcs12ProtectedConfigurationProvider.Pkcs12ProtectedConfigurationProvider, PKCS12ProtectedConfigurationProvider, Version=1.0.0.0, Culture=neutral, PublicKeyToken=34da007ac91f901d"/>
</providers>
</configProtectedData>
之后,我将加密的<connectionStrings> 部分移动到 Web.Release.config(用于在部署到 Azure 时转换 Web.config),并注释该部分以替换 Web.config 中的相应部分:
connectionStrings configProtectionProvider="CustomProvider" xdt:Transform="Replace">
...
</connectionStrings>
最后我在 Web.config 中恢复了开发<connectionStrings> 部分。我已经测试了这个解决方案,发现部署的 Web.config 包含加密的<connectionStrings> 部分,就像我之后一样。