.NET Core console application, how to configure appSettings per environment?

后端 未结 7 957
囚心锁ツ
囚心锁ツ 2020-12-04 14:15

I have a .NET Core 1.0.0 console application and two environments. I need to be able to use appSettings.dev.json and appSettings.test.json based on

7条回答
  •  -上瘾入骨i
    2020-12-04 14:39

    You can do this for ASP.Net Core environment variable (ASPNETCORE_ENVIRONMENT): -

    using Microsoft.AspNetCore.Hosting;
    using System;
    
    public class Program {
        private static string HostingEnvironment => Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
        private static bool IsEnvironment(string environmentName) => HostingEnvironment?.ToLower() == environmentName?.ToLower() && null != environmentName;
    
        private static bool Development => IsEnvironment(EnvironmentName.Development);
        private static bool Production => IsEnvironment(EnvironmentName.Production);
        private static bool Staging => IsEnvironment(EnvironmentName.Staging);
    
        public static void Main(string[] args) { // Your code here }
    }
    

    Then you can simply use the property

        public static void Main(string[] args) {
            if (Development){
                // Blow up the planet
            }
        }
    

提交回复
热议问题