Referring to a separate file for connection strings for appsettings.json?

Viewed 1818

In my .net framework projects I like to have the following in my app.config

 <connectionStrings configSource="connections.config" />

with connections.config containing something like

 <connectionStrings>

   <add name="ApplicationDatabase" providerName="System.Data.SqlClient" connectionString="Server=.\SQLEXPRESS;Database=mydatabase;User Id=myuser; PWD=mypassword;"  />

</connectionStrings>

Then I don't check connections.config into source code.

I want to use a similar trick with .NET Core, but it makes use of appsettings.json

via

     services.AddDbContext<ApiDbContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("MyDatabase")));

How do I proceed?

2 Answers

You can create a separate JSON file (or XML, or any of the configuration providers) and load that at application startup:

WebHost.CreateDefaultBuilder(args)
    .ConfigureAppConfiguration(builder =>
    {
        builder.AddJsonFile("connectionstrings.json", optional: true);
    })

Take a look at the docs for all the supported configuration providers.

For those who would encounter similar situation when they want to secure the connection string (or any other sensitive values) can simply use User Secrets. In Visual Studio (tested on 2019) right clicking on the project, then clicking on "Manage User Secrets" would open secrets.json file that is a hidden file. Keys/values can be entered here just like appsettings.json file.

Related