Using Env Variables In AppSettings.Json

RDoZZ

New member
Joined
Jun 30, 2022
Messages
4
Programming Experience
3-5
I am trying to hide my server username and password in my default connection string. I have environment variables I set in the default config menu of visual studio, but how would I go about referencing them from default config? I can't use any string interpolation there.

{
"ConnectionStrings": {
"DefaultConnection": "server=localhost,1433;database=PizzaPlaceDb;user={SERVER_USERNAME};password={SERVER_PASSWORD};"
},
 
As far as I know there is no default substitution/expansion of environment variables within file configuration providers because environment variables themselves can be used by .NET as a configuration provider. If there was substitution/expansion, then it would be dependent on the order that the configuration providers are listed. Since the default is that environment variables come after file providers, you would have a chicken and egg problem.

My recommendation is to use the SQLCONNSTR_ environment variables. (See the link I'll post below.)

If you really want to use your current approach, you'll need to do the substitution/expansion yourself. It should be relatively easy using Replace().

 
I am still confused about the implementation. I am wondering if I can use these variables I set in db context for the default connection.

Program.cs:
var username = Environment.GetEnvironmentVariable("SERVER_USERNAME");
var password = Environment.GetEnvironmentVariable("SERVER_PASSWORD");

//Add Db Context
builder.Services.AddDbContext<ApplicationDbContext>(options =>
{
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
});
 
Back
Top Bottom