---
# System prepended metadata

title: 依照環境決定讀哪個 appsetting.json 的方法
tags: [.NetCore]

---

# 依照環境決定讀哪個 appsetting.json 的方法
###### tags: `.NetCore`

## 前言
讓本機開發讀 appsettings.Development.json & 其餘(Ex.正式)環境讀 appsettings.json 的方法

## 如何判定是否為正式環境、開發環境 ?
### 非 VS 開發工具啟動的

電腦環境變數沒有特別設置的話，為 `Production`：正式環境，除非特別去電腦環境變數配置 `ASPNETCORE_ENVIRONMENT` 參數
![](https://i.imgur.com/QhpH35L.png)

### 那在 VS 開發工具為什麼是開發環境呢 ?
微軟在偵錯這邊有進行配置
![](https://i.imgur.com/UVB71Sy.png)


## Program.cs

```
public class Program
{
    // 若在這邊需要用到 Config 時，可以像這樣宣告出來，在 CreateHostBuilder 方法中配置讀取哪個 Config 的時候順便 Build 出來
    private static IConfigurationRoot _ConfigurationRoot;
    
    public static void Main(string[] args)
    {
        var host = CreateHostBuilderAndSetConfigurationRoot(args).Build();

        // 這段是在讓 Code First 去 Migrate DB
        using (var scope = host.Services.CreateScope())
        {
            var services = scope.ServiceProvider;
            try
            {
                var context = services.GetRequiredService<DataContext>();
                var userManager = services.GetRequiredService<UserManager<AppUser>>();
                context.Database.Migrate();
                Seed.SeedData(context, userManager).Wait();
            }
            catch (Exception ex)
            {
                var looger = services.GetRequiredService<ILogger<Program>>();
                looger.LogError(ex, "An error occured during migration");
            }
        }
        
        // 這段是在設置排程
        host.Services.UseScheduler(scheduler =>
        {
            // 每 5 分鐘執行清除 User 的機器編號排程
            scheduler.Schedule<ClearUserMachineNo>().EveryFiveMinutes();
        });

        host.Run();
    }

    public static IHostBuilder CreateHostBuilderAndSetConfigurationRoot(string[] args)
    {
        return Host.CreateDefaultBuilder(args)
         .ConfigureWebHostDefaults(builder =>
         {
             builder.UseStartup<Startup>();
             builder.UseUrls("https://localhost:5002/");
             
             // 配置 Config
             builder.ConfigureAppConfiguration((Action<WebHostBuilderContext, IConfigurationBuilder>)((hostingContext, config) =>
             {
                 var hostingEnvironment = hostingContext.HostingEnvironment;

                 if (hostingEnvironment.EnvironmentName == "Development")
                 {
                     config.AddJsonFile("appsettings." + hostingEnvironment.EnvironmentName + ".json", true, true);
                     _ConfigurationRoot = config.Build();
                     Console.WriteLine($"EnvironmentName: {hostingEnvironment.EnvironmentName}, using appsettings.{hostingEnvironment.EnvironmentName}.json");
                 }
                 else
                 {
                     config.AddJsonFile("appsettings.json", true, true);
                     _ConfigurationRoot = config.Build();
                     Console.WriteLine($"EnvironmentName: {hostingEnvironment.EnvironmentName}, using appsettings.json"); 
                 }
             }));
         });
    }
}
```