美文网首页
.Net Core公用方法读取配置文件的内容

.Net Core公用方法读取配置文件的内容

作者: JADDC | 来源:发表于2019-05-10 17:57 被阅读0次

    参考https://blog.csdn.net/yenange/article/details/82457761

    http://www.mamicode.com/info-detail-2602438.html

      private static string GetCustomSettings(string key)
        {
            var config = new ConfigurationBuilder()
                         .AddInMemoryCollection()
                         .SetBasePath(Directory.GetCurrentDirectory())
                         .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                         .Build();
    
            return config.GetSection("CustomSettings").GetValue(key, string.Empty);
        }
        // 获取自定义value
        public static string WXWarningClosedTemplateID => GetCustomSettings("xxx");
    

    using Microsoft.Extensions.Configuration;
    using System;
    
      namespace ConsoleApp4
    {
    class Program
    {
        //安装 .net core 2.1 完整包
        //install-package Microsoft.AspNetCore.All -version 2.1.0
        //注意不要超过 依赖项->SDK->Microsoft.NETCore.App 的版本,我这里是 2.1.0 
        //否则会无法正常生成和运行
        static void Main(string[] args)
        {
            var builder = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json");
            var configuration = builder.Build();
            Console.WriteLine($"ServerCode:{configuration["ServerCode"]}");
            UserInfo user1 = new UserInfo();
            UserInfo user2 = new UserInfo();
            configuration.GetSection("section0").Bind(user1);
            configuration.GetSection("section1").Bind(user2);
    
            Console.WriteLine(user1.ToString());
            Console.WriteLine(user2.ToString());
            Console.WriteLine($"section0:UserId:{configuration["section0:UserId"]}");
            Console.Read();
        }
    }
    
    public class UserInfo
    {
        public long UserId { get; set; }
        public string UserName { get; set; }
    
        public override string ToString()
        {
            return string.Format($"UserId:{UserId}, UserName:{UserName}");
        }
    }
    }
    

    相关文章

      网友评论

          本文标题:.Net Core公用方法读取配置文件的内容

          本文链接:https://www.haomeiwen.com/subject/xqczoqtx.html