C# – Retrieve and use Windows Azure’s connection strings

azurecconnection-stringweb.config

I've configured connection strings in Azure management portal Configure->Connection Strings (linked resources):

enter image description here

What are these connection strings useful for?

I tried deleting the conn. strings from web.config file, so it should read from here, but it doesn't.

Is there any other way?

Basically I want these connection strings to override the connection strings in web.config to be used in production environment.

I've added the following to the Application_Start method:

var sb = new StringBuilder();
var appConfig = ConfigurationManager.OpenMachineConfiguration();  
foreach (ConnectionStringSettings conStr in appConfig.ConnectionStrings.ConnectionStrings)
  sb.AppendFormat("Name: {0}, ConnectionString: {1}\n", conStr.Name, conStr.ConnectionString);
throw new Exception(sb.ToString());

Here's the result:

Name: LocalSqlServer, ConnectionString: data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true

I tried the above with ConfigurationManager.ConnectionStrings as well and the server (Azure) connection strings were not there.

Best Answer

The connection strings in the Portal allow you to override the connection strings defined in the web.config.

When you're developing locally, you probably use a database located in localhost\SQLExpress or something similar. If you deploy without having set up web.config transformation it would mean that your Web Site running in Windows Azure would still point to localhost\SQLExpress, which isn't something you would want.

The connection strings in the Portal allow you to override existing connection strings which are already defined in the web.config. If your web.config does not contain a connection string with the same name as the one configured in the portal, it will not be added and be accessible at runtime. This might be the issue you're experiencing.

To fix this, simply add a connection string to your web.config file with the same name as the one you have already added to the portal.

Update: Like I already explained in a comment, Windows Azure Web Sites does not physically modify the web.config (source), it does this at runtime. So in order to check which AppSettings and ConnectionStrings are actually available at runtime, try this:

Controller:

public ActionResult Index()
{
  ViewBag.ConnectionStrings =
    ConfigurationManager.ConnectionStrings.Cast<ConnectionStringSettings>();
  ViewBag.AppSettings = ConfigurationManager.AppSettings;
  return View();
}

View:

<h3>ConnectionStrings:</h3>
<ul>
  @foreach (var setting in ViewBag.ConnectionStrings)
  {
    <li>@setting.Name: @setting.ConnectionString</li>
  }
</ul>
<h3>AppSettings:</h3>
<ul>
  @foreach (var s in ViewBag.AppSettings)
  {
    <li>@setting: @System.Configuration.ConfigurationManager.AppSettings[s]</li>
  }
</ul>
Related Topic