How to create environments with appSettings?

Mr Edge 221 Reputation points
2023-02-03T09:02:57.8733333+00:00

In previous projects i could click the Configuration or Debug menu (in the top bar) and set a new Configuration. This was displayed when i expanded web.config and i could use this to change environments to use different database connection strings etc.

Im now using .Net 6 and Visual Studio 2022. I carry out the same steps but the experience isnt as straightforward as it was when using the prior version.

In the new version it seems, i have to add code in the Startup class to perhaps list what environment i need to use which doesnt sound right for some reason. In the old version i could swap from Debug to Home to Staging to Live to get the appropriate environment.

Could someone give me some guidance on how i could do the same if using .Net 6 and customising the appSettings.json file for multiple environments and how to switch between them?

Thanks

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,415 questions
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,207 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,288 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,306 questions
{count} votes

Accepted answer
  1. Reza Aghaei 4,936 Reputation points MVP
    2023-02-03T11:27:15.6266667+00:00

    You can add any environment and different app settings per environment easily. So you don't need to add any code the startup class in ASP.NET Core and everything works by default. You may want to have some code, probably when it comes to have a different feature (not a different config) for different environments (for example, exposing an endpoint just in staging environment), but for app settings, no code. Just go with the configs in proper files and choose the profile to run.

    For example, if you want a different app settings for a new environment called Home, do the followings:

    1. Add a appsettings.Home.json file to the project.
    2. Add the setting to the file, for example:
         {
           "DetailedErrors": true,
           "Logging": {
             "LogLevel": {
               "Default": "Information",
               "Microsoft.AspNetCore": "Warning"
             }
           },
           "MyAppSettings": {
             "Title": "Hello from Home environment!"
           }
         }
      
    3. Add the value for the other environments as well.
    4. Now to choose the profile or environment, open launchSettings.json which is under Properties folder and set the environment in ASPNETCORE_ENVIRONMENT:
         {
           "iisSettings": {
             "windowsAuthentication": false,
             "anonymousAuthentication": true,
             "iisExpress": {
               "applicationUrl": "http://localhost:5061",
               "sslPort": 0
             }
           },
           "profiles": {
             "Home": {
               "commandName": "Project",
               "dotnetRunMessages": true,
               "launchBrowser": true,
               "applicationUrl": "http://localhost:5110",
               "environmentVariables": {
                 "ASPNETCORE_ENVIRONMENT": "Home"
               }
             },
             "IIS Express": {
               "commandName": "IISExpress",
               "launchBrowser": true,
               "environmentVariables": {
                 "ASPNETCORE_ENVIRONMENT": "Development"
               }
             }
           }
         }
      

    This basically enables the Home environment:

    User's image

    Now when you run the application, it will read the app settings from the environment that you specified in launchsettings.json.

    You can define or add any other environment that you want, using the lunchsettings.json or using the project properties as mentioned in the other answer.

    To see it in action:

    @page
    @using Microsoft.Extensions.Configuration
    @inject IConfiguration Configuration
    @model IndexModel
    @{
        ViewData["Title"] = "Home page";
    }
    
    
        @Configuration.GetSection("MyAppSettings")["Title"]
    
    
    

    And if you run the app, with Home profile:

    User's image

    To learn more take a look at following resources:

    1 person found this answer helpful.

2 additional answers

Sort by: Most helpful
  1. Karen Payne MVP 35,196 Reputation points
    2023-02-03T11:40:48.6433333+00:00

    Create an appsetting file for each environment e.g. appsettings.Development.Json

    2222

    Then in Startup

    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
    
    
    Configuration = builder.Build();
    }
    

    Next, in debug properties, set the environment.

    11111

    For going live, create an environment variable on the server if one server or if you have dedicated servers set them accordingly.

    See also, the following stackoverflow post.

    Here is an example I did for a contract.

    2 people found this answer helpful.

  2. xmax11 20 Reputation points
    2023-02-05T14:56:40.5166667+00:00
    In .NET, you can use the appSettings section of the configuration file (usually Web.config or App.config) to store configuration values. You can create separate environments by having different configuration files for each environment, and then switch between them based on the current environment. Here's how you can do this:
    
    Create separate configuration files for each environment, such as Web.config, Web.Development.config, Web.Staging.config, and Web.Production.config.
    
    In the main configuration file (Web.config), define the values that are common to all environments.
    
    In each of the environment-specific configuration files (e.g., Web.Development.config), add or modify the values as needed for that environment.
    
    Use the transform feature in Visual Studio to automatically apply the environment-specific configuration when you build your application.
    
    Determine the current environment in your code and choose the appropriate configuration file to use. You can do this by using an environment variable, checking a command-line argument, or using a method of your own choosing.
    
    Here's an example of what a Web.config file might look like:
    
    php
    Copy code
    <configuration>
      <appSettings>
        <add key="Key1" value="Value1" />
        <add key="Key2" value="Value2" />
      </appSettings>
    </configuration>
    And here's an example of what a Web.Development.config file might look like:
    
    php
    Copy code
    <configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
      <appSettings>
        <add key="Key2" value="DevelopmentValue2" xdt:Transform="SetAttributes" xdt:Locator="Match(key)" />
      </appSettings>
    </configuration>
    The transform feature will automatically apply the values from the environment-specific configuration file when you build the application, so that the appSettings section in the final configuration file will contain the values specific to the environment you are building for.
    
    0 comments No comments