.NET Core读取appsettings.json参数

读取appsettings.json参数目的就是为了方便修改。

首先装两个包:

Microsoft.Extensions.Configuration.FileExtensions

Microsoft.Extensions.Configuration.Json

 /// 
    /// 读取配置文件
    /// 
    public class AppConfiguration
    {
        private static readonly string CONFIG_FILE = "appsettings.json";  // 配置文件地址
        private static IConfiguration Configuration;  // 配置信息

        /// 
        /// 获取配置文件
        /// 
        /// 
        private static void GetConfiguration()
        {
            try
            {
                if (Configuration == null)
                {
                    var build = new ConfigurationBuilder();
                    build.SetBasePath(Directory.GetCurrentDirectory());  // 获取当前程序执行目录
                    build.AddJsonFile(CONFIG_FILE, true, true);
                    Configuration = build.Build();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// 
        /// 获取配置文件信息
        /// 
        /// 多个节点可以用英文.号隔开
        /// 
        public static string GetJsonInfo(string configKey)
        {
            try
            {
                GetConfiguration();
                if (configKey.Contains("."))
                {
                    IConfigurationSection child = null;
                    foreach (string key in configKey.Split('.'))
                    {
                        if (child == null)
                            child = Configuration.GetSection(key);
                        else
                            child = child.GetSection(key);
                    }

                    return (child == null) ? "" : child.Value;
                }
                else
                {
                    return Configuration.GetSection(configKey).Value;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

    }

然后直接调用即可:

AppConfiguration.GetJsonInfo("??");

你可能感兴趣的:(后端,.netcore,开发语言)