zoukankan      html  css  js  c++  java
  • ASP.NET Core 类库中取读配置文件

    在程序中经常遇到读取指定Json文件的内容,并把其转换成指定的Model对象,应该如何做呢?

    首先要创建需要转换的Model类。

    转换方法如下:

             public static T GetAppSettings<T>(string fileName, string key) where T : class, new()
            {
                // 获取bin目录路径
                var directory = AppContext.BaseDirectory;
                directory = directory.Replace("\", "/");
    
                var filePath = $"{directory}/{fileName}";
                if (!File.Exists(filePath))
                {
                    var length = directory.IndexOf("/bin");
                    filePath = $"{directory.Substring(0, length)}/{fileName}";
                }
    
                IConfiguration configuration;
                var builder = new ConfigurationBuilder();
    
                builder.AddJsonFile(filePath, false, true);
                configuration = builder.Build();
    
                var appconfig = new ServiceCollection()
                    .AddOptions()
                    .Configure<T>(configuration.GetSection(key))
                    .BuildServiceProvider()
                    .GetService<IOptions<T>>()
                    .Value;
    
                return appconfig;
            }
    

      上面的方法是给定bin目录下指定的json文件名和指定的Key,然后就可以把指定Key下面的Json内容转换成指定的Model对象。

  • 相关阅读:
    leetcode回溯总结
    排序算法详解
    Java核心基础知识泛型
    leetcode贪心算法
    Linux虚拟机配置及安装Redis
    HJ6质数因子
    冒泡排序(升序)
    动态规划 背包问题
    配置mycatschema.xml
    HJ106字符逆序
  • 原文地址:https://www.cnblogs.com/zunzunQ/p/11906338.html
Copyright © 2011-2022 走看看