.net 6 读取web.confg配置

以下代码的源代码仓库:https://gitee.com/shllong/.net-Read-webConfig/tree/master

引用包:
Microsoft.Extensions.Configuration 配置类库
Microsoft.Extensions.Configuration.Binder 将配置转换为实体类的类库
Microsoft.Extensions.Configuration.FileExtensions 需要重写的类

1. 创建一个web.config文件,并修改属性->复制到输出目录->如果较新则复制

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
	<connectionStrings>
		<add name="conn1" connectionString="service=.;database=myschool;uid=sa;pwd=sa;" providerName="sql server"/>
		<add name="conn2" connectionString="service=127.0.0.1;database=myschool;uid=sa;pwd=sa;" providerName="mysql"/>
	</connectionStrings>
	<appSettings>
		<add key="name" value="张三"/>
		<add key="age" value="22"/>
		<add key="students:name" value="张同学"/>
		<add key="students.age" value="11"/>
		<add key="students:scores:0" value="100"/>
		<add key="students:scores:1" value="88"/>
	</appSettings>
</configuration>

2. 创建配置文件的实体类

配置文件读取到后转换为实体类

internal class Student
{
    public string Name { get; set; }
    public int Age { get; set; }
    public int[] Scores { get; set; }
}
internal class Teacher
{
    public string Name { get; set; }
    public int Age { get; set; }
    public Student Students { get; set; }
}
internal class ConnStr
{
    public string Name { get; set; }
    public string ConnectionString { get; set; }
    public string ProviderName { get; set; }
}
internal class Config
{
    public List<ConnStr> ConnStrs { get; set; }
    public Teacher teacher { get; set; }
	// 测试时候使用输出
    public override string ToString()
    {
        string connStr = "";
        foreach (ConnStr con in this.ConnStrs)
        {
            connStr += $"连接字符串名称:{con.Name} 连接字符串:{con.ConnectionString} 使用的数据库:{con.ProviderName};\n";
        }
        return $"连接字符串:{connStr}老师名称:{teacher.Name} 老师年龄:{teacher.Age} \n" +
            $"学生名称:{teacher.Students.Name} 学生年龄:{teacher.Students.Age} \n" +
            $"学生成绩:{string.Join(",", teacher.Students.Scores)}";
    }
}

3. 创建FxConfigProvider类继承自FileConfigurationProvider

internal class FxConfigProvider : FileConfigurationProvider
{
    public FxConfigProvider(FileConfigurationSource source) : base(source)
    {
    }

    public override void Load(Stream stream)
    {
        // 创建一个不区分大小写的哈希表
        Dictionary<string,string> dic = new Dictionary<string,string>(StringComparer.OrdinalIgnoreCase);
        // 创建一个读取xml文档的工具类
        XmlDocument xmlDocument = new XmlDocument();
        // 初始化
        xmlDocument.Load(stream);
        // 处理连接字符串数据
        XmlNodeList connStrs = xmlDocument.SelectNodes("/configuration/connectionStrings/add");
        int i = 0;
        foreach(XmlNode node in connStrs.Cast<XmlNode>())
        {
            string name = node.Attributes["name"].Value;
            string connectionString = node.Attributes["connectionString"].Value;
            var providerName = node.Attributes["providerName"];
            if(providerName != null)
            {
                dic["ConnStrs:" + i + ":providerName"] = providerName.Value;
            }
			// 将数据进行扁平化处理
            dic["ConnStrs:" + i + ":ConnectionString"] = connectionString;
            dic["ConnStrs:" + i + ":name"] = name;
            i++;
        }
        // 处理appSettings中的数据
        connStrs = xmlDocument.SelectNodes("/configuration/appSettings/add");
        foreach (XmlNode node in connStrs.Cast<XmlNode>())
        {
            string key = node.Attributes["key"].Value;
            key = key.Replace(".",":");
            string value = node.Attributes["value"].Value;
            dic["teacher:" + key] = value;
        }
        // 将处理好的哈希表数据放到FileConfigurationProvider的Data数据中
        this.Data = dic;

    }
}

数据扁平化处理:

  1. Student.Name = Student:Name
  2. Student.Scores[0] = Student:Scores:0
  3. Student.Scores[1] = Student:Scores:1

4. 创建FxConfigSource类继承自FileConfigurationSource

这个类主要用来处理参数

internal class FxConfigSource : FileConfigurationSource
{
    public override IConfigurationProvider Build(IConfigurationBuilder builder)
    {
        EnsureDefaults(builder);
        return new FxConfigProvider(this);
    }
}

5. 在Main函数中使用

static void Main(string[] args)
{
    // 创建读取文件的工具类
    ConfigurationBuilder builder = new ConfigurationBuilder();
    // 将web.config文件添加到工具类中
    builder.Add(new FxConfigSource() { Path = "web.config"});
    // 初始化
    IConfigurationRoot root =  builder.Build();
    // 将配置文件映射为实体类
    Config config = root.Get<Config>();
    // 输出实体类数据
    Console.WriteLine(config.ToString());
    Console.ReadKey();
}
posted @ 2023-11-30 11:40  Simian_2018_12_22  阅读(92)  评论(0编辑  收藏  举报