Matthew Verstraete
Matthew Verstraete

Reputation: 6781

ASP.NET 5/EF7 connection string in web.config?

In ASP.Net 4.5 I could put my connection string in the web.config as to take advantage of web.config transformations so I could work locally with the development DB and then when I publish it would point to the production DB. I am now working with ASP.Net 5 and EF 7 which seems to use the config.json file to store connection strings instead of the web.config. With this new way of storing files I can not figure out how to do something like the web.config transformations from the past. How can I either setup config.json to do this OR configure it so I can do it in the web.config and have EF look there for the strings?

Upvotes: 4

Views: 6671

Answers (2)

Oleg
Oleg

Reputation: 221997

The web.config transformation syntax is oriented on XML format of data. The new configurations consist of some files in JSON format and one can implement staging scenarios very easy.

First of all ASP.NET supports allows to set destination environment by usage ASPNET_ENV environment variable or by setting Hosting:Environment in launchSettings.json file (see Properties folder of your project). The file launchSettings.json can be modified in Visual Studio in properties of the project. One should first choose the "Profile"

enter image description here

and make setting for every profile. Alternatively one can just edit the file Properties\launchSettings.json manually.

Some configuration files, like hosting.json works automatically using staging. Thus you can set for example different ports and different interface binding by specifying server.urls in hosting.json and hosting.Development.json for example.

To include staging logic in appsettings.json one need modify the constructor of Startup class in Startup.cs. For example:

public class Startup
{
    public static IConfigurationRoot Configuration { get; set; }

    public Startup(IHostingEnvironment env)
    {
        // Set up configuration sources.
        var builder = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json")
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", true)
            .AddEnvironmentVariables();
        Configuration = builder.Build();
    }

    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddMvc()
            .AddJsonOptions(options => {
                options.SerializerSettings.ContractResolver =
                    new CamelCasePropertyNamesContractResolver();
            });
        services.AddEntityFramework()
            .AddSqlServer()
            .AddDbContext<MyContext>(options => {
                options.UseSqlServer(Configuration["Data:ConnectionString"]);
            })
            .AddDbContext<SM9Context>(options => {
                options.UseSqlServer(Configuration["Data:SM9ConnectionString"]);
            });
    }
}

The above code saves configuration in Configuration property and then uses ConfigureServices to make injection of MyContext and SM9Context database contexts. One can for example create main appsettings.json file with all productive configuration and create appsettings.Development.json file which overrides only one (from two Data:ConnectionString and Data:SM9ConnectionString) connection string:

{
  "Data": {
    "ConnectionString": "Server=..."
  }
}

ASP.NET will combine both files appsettings.json and optional appsettings.Development.json to create the full set of configuration parameters.

The article and the part of documentation describes how one can use the staging in ASP.NET 5.

Upvotes: 3

Stafford Williams
Stafford Williams

Reputation: 9806

You can do something like this to pull in configs from different *.json files, the following bases them on environment, or from environment variables;

var builder = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json")
    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
    .AddEnvironmentVariables();

You can also use the ASPNET secret manager.

Each time a config that is accessed, it will override the settings for any config values it has, meaning the variable will reflect whatever it was set to last.

Check out the docs on Configuration.

Upvotes: 2

Related Questions