appsettings.json和appsettings.Development.json

发布时间 2023-12-06 16:44:13作者: ProZkb

ASP.NET Core 中,当应用程序处于开发环境时,默认情况下会加载 appsettings.jsonappsettings.Development.json 文件中的配置,

并且 appsettings.Development.json 中的配置会覆盖 appsettings.json 中的相同配置。这是 ASP.NET Core 提供的一种便捷的配置管理机制。

如果你希望在不同的环境中使用不同的连接字符串,可以按照以下步骤操作:

  1. 确保 appsettings.json 文件中包含通用的配置,而 appsettings.Development.json 中包含开发环境特定的配置。

  2. Startup.cs 中的 ConfigureServices 方法中,可以根据需要设置当前环境:

    public void ConfigureServices(IServiceCollection services, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            // 在开发环境中读取 appsettings.Development.json 的配置
            var config = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json")
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .Build();
            services.AddSingleton<IConfiguration>(config);
        }
        else
        {
            // 在其他环境中只读取 appsettings.json 的配置
            var config = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json")
                .Build();
            services.AddSingleton<IConfiguration>(config);
        }
    
        // 其他服务的注册...
    }