Blazor and appsettings.Testing.json

1.3k Views Asked by At

I would like to be able to use appsettings.json, appsettings.Testing.json to retrieve appropriate connection string for my blazor application. On testing server, I set the system variable "ASPNETCORE_ENVIRONMENT" to "Testing" and I have appsettings.Testing.json with connection string. For some reason when accessing the app via browser, the connection string is retrieved from appsettings.json and not appsettings.Testing.json.

If I change/override the environment variable from launchSettings.json in my local environment, and launch the application from IIS express, it picks up the correct connection string. Is there anything I need to do in the startup.cs?

Here is my Startup.cs

public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

Here is my appsettings.Testing.json:

{
  "_comment": "Environment settings for testing environment",
  "ConnectionStrings": {
    "DBConnectionString": "Server=TEST-SERVER102;Database=Customers;Trusted_Connection=True;"
  }
}

enter image description here

UPDATE: If logged the current environment using below code:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            Debug.WriteLine("[Current Environment]" + env.EnvironmentName);

I see below log statement: [Environment]Production

I read on microsoft documentation that if environment is not set, it defaults to Production. I did set the environment to "Testing" via system variable. What am I missing?

2

There are 2 best solutions below

0
On

It turns out that on my testing server where the application is hosted in IIS 10 in its own application pool, I have to set the environment variable ASPNETCORE_ENVIRONMENT via appcmd.exe.

appcmd.exe set config -section:system.applicationHost/applicationPools /+"[name='Contoso'].environmentVariables.[name='foo',value='bar']" /commit:apphost

1
On

Did you restart your console after setting global environment variable (unless you set it in current terminal session)?

Make sure you followed the rules metioned in ASP.NET Core docs related to your OS: Set the environment.