azure - 在服务配置中设置应用程序 ConnectionString 而不是 Azure 中的 web.config

标签 azure web-config connection-string azure-cloud-services azure-configuration

我当前在 Azure 中有一个应用程序,每当我们将其推送到 Staging 段时,我们都无法真正进行测试,因为连接字符串指向 prod 数据库。

有人向我提到,您应该能够在 ServiceConfiguration.cscfg 文件中设置连接字符串,而不是(或使用)web.config 文件。这样,您就可以更改 Azure 门户中的连接字符串,而无需重新发布 who 应用程序。

有人知道怎么做吗?

最佳答案

在 ServiceConfiguration.cscfg 文件中添加:

<ServiceConfiguration ... />
  <Role ... />
    <ConfigurationSettings>
      <Setting name="DatabaseConnectionString" value="put your connection string here" />
    </ConfigurationSettings>
  </Role>
</ServiceConfiguration>

现在您有了一个连接字符串,可以通过编辑 Azure 门户内的配置来更改它。

然后,只要您需要检索连接字符串,您就可以使用:

using Microsoft.WindowsAzure.ServiceRuntime;

...

String connString = RoleEnvironment.GetConfigurationSettingValue("DatabaseConnectionString")

您可能需要将 Microsoft.WindowsAzure.ServiceRuntime.dll 添加到您的引用中。

RoleEnviroment.IsAvailable 可用于测试您是否在 Azure 中运行,如果没有则回退到您的 web.config 设置。

using System.Configuration;
using Microsoft.WindowsAzure.ServiceRuntime;

...

if (RoleEnvironment.IsAvailable)
{
    return RoleEnvironment.GetConfigurationSettingValue("DatabaseConnectionString");
}
else
{
    return ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString; 
}

This article has a more verbose explanation of the above.

关于azure - 在服务配置中设置应用程序 ConnectionString 而不是 Azure 中的 web.config,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5979562/

相关文章:

asp.net - IIS中的Web配置错误

mongodb - 蒙戈错误: auth failed mongoose connection string

azure - 向通知中心注册两个模板并发送通知

Azure 媒体播放器预览图像

Azure 流 URL 有效性

c# - Npgsql conn.Open() 不起作用

sql-server-2008 - SQL Server "."别名不工作

azure - 使用 Azure 网格事件触发 ADF Pipe 将本地 CSV 文件移动到 Azure 数据库

web-config - ASP.NET Core 2 中的 web.config

asp.net-mvc - Elmah.MVC 在 IIS Express 下工作,但不能在 IIS 7.5 下工作