How to configure ASP.NET Core to have different configurations for two deployed applications

1.6k Views Asked by At

I've been learning about ASP.NET environment variables and configurations.

I see that, by default, any settings placed in appsettings.Development.json will override the same settings in appsettings.json when running in my own local environment. And that appsettings.Development.json is not deployed and so does not override any settings when deployed.

My question: Does anyone know a way to use this same mechanism for multiple deployed configurations?

For example, I have a website and a demo version of the website. Both use the same code base but a couple of settings need to be different for the demo site. It would be great if I could create appsettings.Demo.json and place any settings in there that need to be overridden just for the demo site.

Currently, I just set an IsDemoSite setting in the file. This works but it would be much more elegant if I could have different configuration settings.

I haven't been able to find any documentation about having different configurations when deployed.

Also, one of the differences is that the demo site uses a different database connection string. And so I would need to be able to set which version I'm working on when running migrations, etc.

1

There are 1 best solutions below

10
On

Well, I had the same thing to do - Your on track with custom appsettings files.

In my case, I wanted a separate development, production, wsl and docker configuration. Solution - given that I was running prod and dev on separate virtual instances, was to use old and true ASPNETCORE_ENVIRONMENT variable.

I created required variations of appsettings (appsettings.docker etc) and set up aforementioned variable for given files.

In addition as my app starts, it grabs the path to the correct file (part of the name is taken from ASPNETCORE_ENVIRONMENT) and loads it as normal json file to .ConfigureAppConfiguration method of CreateHostBuilder. It works perfectly for my requirements - should be good for You.

You can find example here.

As for setting up ASPNETCORE_ENVIRONMENT - depends on the host system that You are on:

  • For docker
# final stage/image
FROM mcr.microsoft.com/dotnet/aspnet:5.0
WORKDIR /app
COPY --from=publish /app .
ENV ASPNETCORE_ENVIRONMENT="docker"
ENTRYPOINT ["dotnet", "ScanApp.dll"]
  • for Windows:
    Follow this guide - it will guide you through global and in-app settings

  • for WSL - in Your launchSettings.json:

"WSL": {
      "commandName": "WSL2",
      "launchBrowser": true,
      "launchUrl": "https://localhost:5051",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "wsl",
        "ASPNETCORE_URLS": "https://localhost:5051;http://localhost:5050"
      },
      "distributionName": "Ubuntu-20.04"
    }