对于那些也在寻找此问题的解决方案的人,这是我的解决方案(这只是一种可能的解决方案)。
在我的 Web.config 类中,我使用 configSource 作为连接字符串:
<connectionStrings configSource="connections.config"/>
然后我使用静态方法在我的 App_Start 文件夹中创建了一个类:
public static void CloneEnvironmentConfigSource()
{
String path = AppDomain.CurrentDomain.BaseDirectory;
Debug.WriteLine("Path = " + path);
try
{
File.Copy(path + @"..\EnvironmentConfig\connections.config", path + @"connections.config", true);
}
catch (Exception ex)
{
Console.WriteLine(ex);
throw ex;
}
}
我在 Global.asax.cs 文件的 Application_Start() 中调用了这个方法……就像这样:
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
ConnectionStringBuilder.CloneEnvironmentConfigSource();
基本上,我在环境中有一个文件夹,我将“部署”我的应用程序,其中存储了我的 configSource 文件,该文件将被复制到项目中以供 Web.config 参考。
我不得不求助于这个,因为 configSource url 映射不允许您进入其自身之上的目录。因此,这使我可以将我的项目部署到任何环境,而不必担心更改用于开发或测试的连接字符串信息。
希望这对某人有所帮助,如果此解决方案将来会出现问题或有人认为会有负面影响,请告诉我。
*** 只是一个更新。我遇到了一个问题,即 Application_Start() 被多次调用并减慢了我的应用程序。我认为这是因为此时 Web.config 被更改,框架已经加载了 web.config,所以它进行了更改并重新加载了所有内容。
我必须做的是使用 ConnectionStringBuilder.CloneEnvironmentConfigSource();从 Application_Start() 中取出并将其放入 AssemblyInfo.cs 中:
//Called to set config file dynamicaly used by Web.config file to set connectionstring.
//Has to be one of the first methods ran to avoid reload of Web.config after changes are made.
[assembly: PreApplicationStartMethod(
typeof(ConnectionStringBuilder), "CloneEnvironmentConfigSource")]
这样它会在其他任何东西之前运行。