net core 3.1 读取appsettings.json配置文件


.NET CORE 3.0新增了Worker Services的新项目模板,可以编写长时间运行的后台服务,并且能轻松的部署成windows服务或linux守护程序。

读取appsettings.json配置文件

{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"ConnectionStrings": {
"sqlserverContext": "sqlserverContextvalue",
"mysqlContext": "mysqlContextvalue"
}
}

读取ConnectionStrings

Main方法中添加代码

public static void Main(string[] args)
{
  var builder = new ConfigurationBuilder();   builder.AddJsonFile("appsettings.json",true,true);   IConfigurationSection conf = builder.Build().GetSection("ConnectionStrings");   AppSettings.SetAppSetting(conf);   CreateHostBuilder(args).Build().Run(); }
第一个GetSection定位第一层位置,比如ConnectionStrings,
第二个GetSection定位第二层位置,选择ConnectionStrings中的sqlserverContext或mysqlContext

新建AppSettings类

    public class AppSettings
    {
        private static IConfigurationSection appSection = null;
        /// <summary>
        /// 获取配置文件
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetAppSeting(string key)
        {
            if (appSection.GetSection(key) != null)
            {
                return appSection.GetSection(key).Value;
            }
            else
            {
                return "";
            }
        }
        /// <summary>
        /// 设置配置文件
        /// </summary>
        /// <param name="section"></param>
        public static void SetAppSetting(IConfigurationSection section)
        {
            appSection = section;
        }
    }
 private string ConnStr = AppSettings.GetAppSeting("mysqlContext");

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM