$ cat "

Managing Connection Strings with ASP.NET vNext and Azure Web Apps

"

At the time of writing this post ASP.NET vNext (5) is in beta 4. The googleability is still low, and the majority of the information is incomplete or is written for an earlier beta, often with breaking code changes between the beta versions.

One of the areas where I had problems finding information was connection string management in the new configuration system.

The problem I wanted to solve was how to define connection strings for the production environment of an open source project, without having to check in any credentials or having to distribute credentials to all team members in some other way. I had seen that the Azure portal has a section for connection strings in the settings of a web app, but I could not find information about how those connection strings were injected into the app config.

As it turns out, the best source of information for this kind of stuff is the default project template for a vNext MVC 6 application (NOT the WebAPI template). The default template contains configuration code for lots of basic stuff, including Entity Framework 7 configuration.

Enough talk, this is the way to handle connection strings to be able to override them from the Azure portal:


// Config.json:

{
"Data": {
"DefaultConnection": {
"ConnectionString": "Server=.;Database=TaskBoard;User Id=some_user;Password=some_password;"
}
},
"EntityFramework": {
"ApplicationDbContext": {
"ConnectionStringKey" : "Data:DefaultConnection:ConnectionString"
}
}
}


// Startup.cs:

public class Startup
{
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();

services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<BoardContext>();
}

public void Configure(IApplicationBuilder app)
{
app.UseMvc()
.UseStaticFiles();
}
}


// DbContext class:

public class SomeContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var config = new Configuration()
.AddJsonFile("config.json")
.AddEnvironmentVariables();

// The development connection string is defined in the config.json file.
// The connection strings for the Azure web app(s) are defined in the web app
// settings in the Azure portal
optionsBuilder.UseSqlServer(config["Data:DefaultConnection:ConnectionString"]);

base.OnConfiguring(optionsBuilder);
}

Written by Erik Öjebo 2015-06-09 21:39

    Comments