App Settings file according to environment variable - DotNet Core API
Updated: Jun 2, 2020
In today’s article, we will see how we can have multiple appsettings file according to our environment in ASP.NET Core API.
Why do we need this?
In a real-world application, we normally have multiple environments for our applications such as development, staging, production etc. and according to these environments we have multiple values for the same keys. A primary example for this is we usually have different databases for different environments. So, this article will tell you how can you use environment based appsettings file without having changing the values manually for each environment.
Let’s get started.
Create a project in visual studio for ASP.NET Core API
After these steps your project will be created and it will look something like this
If you expand appsettings.json you will see appsettings.Development.json. DotNet core automatically creates this file for you
Now we will add a section in appsettings.json
"DbConnection": "my prod db connection",
Now we will add a section in appsettings.Development.json
"DbConnection": "my development db connection",
You see that these are the same sections but with different values.
Now our appsettings.json file looks something like this
Now our appsettings.Development.json file looks something like this
Now we will add the code to read values from appsettings.json
Now if you open Properties folder and open launchSettings.json and you will see the ASPNETCORE_ENVIRONMENT variable and it’s value is Development.
After adding the code to read appsettings values our controller looks something like this
Now we will add another appsettings file for staging environment and we will name it as appsettings.Staging.json. Add a file by right clicking on the project and click on add item
Our project structure will look like this
Now we will add MySettings section in this (appsettings.Staging.json) file also
"DbConnection": "my staging db connection",
Now our appsettings.Staging.json will look like this
Now at our controller we will add a breakpoint to debug our code
Now we will run our application, and since in launch settings our ASPNETCORE_ENVIRONMENT variable is Development so our code should read the value from development file
We can see that our code is reading from development file.
Now let’s change our ASPNETCORE_ENVIRONMENT value to Staging
Now let’s run it again
In this article we have seen how we can have multiple appsettings file and use them according to the ASPNETCORE_ENVIRONMENT variable.
If you wish to see the code please Click Here!