ASP.NET Core applications use appsettings.json
file storage configuration settings, including database connection strings and API URLs, etc. However, these settings usually vary by development environment (local, test, production). To solve this problem, ASP.NET Core provides a flexible mechanism to load different appsettings
files based on the build configuration.
solution involves creating multiple appsettings
files such as appsettings.Production.json
and appsettings.Development.json
. Each file contains configuration settings specific to the corresponding environment.
In order to automatically load the corresponding appsets
file, you can use the Host.CreateDefaultBuilder
method of ASP.NET Core. This method initializes the configuration object according to the following sources in the following order:
appsettings.json
appsettings.{Environment}.json
(for example appsettings.Development.json
)The configuration system will automatically load the corresponding appsettings.{Environment}.json
environment variable to the desired environment (for example, "Production" or "Development").
Environment variable settings
Visual Studio: Project > Properties > Debug > Environment Variables
env
]
Startup settings: Properties/launchSettings.json > environmentVariables:
WebHost.CreateDefaultBuilder(args)
.UseStartup()
.Build();
Startup class, the configuration object will be automatically injected:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
}
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3