【问题标题】:Substituting values into web.config at runtime在运行时将值替换到 web.config
【发布时间】:2011-05-25 20:00:16
【问题描述】:

我们有一个在三个环境中运行的应用程序:开发、QA 和生产。该应用程序访问一个 SQL 服务器和几个 Web 服务。 web.config 文件包含 SQL 服务器的连接字符串和 Web 服务的 IP 地址。我们希望能够拥有一个适用于所有三种环境的 web.config 文件,但以某种方式获取每种环境的不同数据。有谁知道这样做的方法吗?

【问题讨论】:

    标签: asp.net parameters web-config string-substitution


    【解决方案1】:

    【讨论】:

    • 感谢您的出色参考。我不知道这种能力存在。
    【解决方案2】:

    我们使用与您完全相同的配置选项,并且我们在 web.config 中创建了 3 个连接字符串,如下所示:

    <connectionStrings>
        <add name="Dev" connectionString="Server=localhost;Database=WebDev;User=devo;Pwd=xxxxx;" providerName="System.Data.SqlClient"/>
        <add name="Stage" connectionString="Server=localhost;Database=WebStage;User=stago;Pwd=xxxxx;" providerName="System.Data.SqlClient"/>
        <add name="Live" connectionString="Server=localhost;Database=WebLive;User=livo;Pwd=xxxxx;" providerName="System.Data.SqlClient"/>
    </connectionStrings>
    

    然后我们有一个静态方法,它基于 url 来确定使用哪个 conn str:

    public static string ConnStr
    {
        get
        {
            if (Config.WebRoot.StartsWith("http://www.")) { return ConfigurationManager.ConnectionStrings["Live"].ToString(); }
            else if (Config.WebRoot.StartsWith("http://stage.")) { return ConfigurationManager.ConnectionStrings["Stage"].ToString(); }
            else if (Config.WebRoot.StartsWith("http://localhost")) { return ConfigurationManager.ConnectionStrings["Dev"].ToString(); }
            else { return null; }
        }
    }
    

    您可能需要调整方法以适合您。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-29
      • 2015-10-11
      • 2019-03-25
      • 1970-01-01
      • 2018-07-13
      • 2012-05-07
      • 1970-01-01
      相关资源
      最近更新 更多