栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > .Net

.Net 6读取json配置文件

.Net 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

.Net 6读取json配置文件

使用.Net 6



  
    Exe
    net6.0
    enable
    enable
  

  
    
    
    
    
      all
      runtime; build; native; contentfiles; analyzers; buildtransitive
    
    
    
    
    
    
    
  

  
    
      PreserveNewest
    
  




建立一个配置文件, 并设置为更新时复制

{
  "name": "zg",
  "age": 18,
  "proxy": {"address": "aa","port": "8080"}
}
// See https://aka.ms/new-console-template for more information
using Microsoft.Extensions.Configuration;


ConfigurationBuilder cfgBuilder = new ConfigurationBuilder();

//optional: true 可以检测报错  reloadOnChange: true 自动加载. json设置成更新时复制
cfgBuilder.AddJsonFile("config.json", optional: true, reloadOnChange: true);
IConfigurationRoot configRoot = cfgBuilder.Build();

Console.WriteLine("--------------原始方法----------------------------------");
string name = configRoot["name"];
Console.WriteLine($"name={name}");

string add = configRoot.GetSection("proxy:address").Value;

Console.WriteLine($"addr={add}");

Console.WriteLine("--------------使用微软的Configuration.Binder----------------------------------");
//使用微软的Configuration.Binder

Proxy proxy = configRoot.GetSection("proxy").Get();
Console.WriteLine($"IP地址是:{ proxy.Address},端口号是{proxy.Port}");


Console.WriteLine("--------------直接读取根节点----------------------------");

Config config = configRoot.Get();

Console.WriteLine($"姓名是{config.Name}, 年龄是{config.Age}, IP地址是:{ config.Proxy.Address},端口号是{config.Proxy.Port}");


class Proxy
{
    public string Address  { get; set; }
    public string Port { get; set; }
}

class Config
{
    public string Name { get; set; }
    public string Age { get; set; }

    public Proxy Proxy { get; set; }
}

结果:

--------------原始方法----------------------------------
name=zg
addr=aa
--------------使用微软的Configuration.Binder----------------------------------
IP地址是:aa,端口号是8080
--------------直接读取根节点----------------------------
姓名是zg, 年龄是18, IP地址是:aa,端口号是8080

E:CsharpConfigTestDemonConfigTestDemonbinDebugnet6.0ConfigTestDemon.exe (进程 8608)已退出,代码为 0。
要在调试停止时自动关闭控制台,请启用“工具”->“选项”->“调试”->“调试停止时自动关闭控制台”。
按任意键关闭此窗口. . .

使用依赖注入的方式:

using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConfigTestDemon
{
    public class TestController
    {
        //private IOptionsSnapshot optConfig;

        private IOptionsSnapshot optConfig;

        public IOptionsSnapshot OptConfig
        {
            get { return optConfig; }
            set { optConfig = value; }
        }



        public TestController(IOptionsSnapshot optConfig) => this.optConfig = optConfig;

        public void Test()
        {
            Console.WriteLine(optConfig.Value.Age);
            Console.WriteLine("---------------");
            Console.WriteLine(optConfig.Value.Proxy.Address);
        }

    }
}

using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConfigTestDemon
{
    public class OnlyProxy
    {
        private IOptionsSnapshot optProxy;

        public OnlyProxy(IOptionsSnapshot optProxy)
        {
            this.optProxy = optProxy;
        }

        public void Test()
        {
            Console.WriteLine($"用OnlyProxy实现IP为{optProxy.Value.Address},端口号为:{optProxy.Value.Port}");
        }
    }
}

//Console.WriteLine("--------------使用DI依赖注入----------------------------");

ConfigurationBuilder cfgBuilder = new ConfigurationBuilder();

//使用CommandLine

//optional: true 可以检测报错  reloadOnChange: true 自动加载. json设置成更新时复制
cfgBuilder.AddJsonFile("config.json", optional: true, reloadOnChange: true);
IConfigurationRoot configRoot = cfgBuilder.Build();

ServiceCollection services = new ServiceCollection(); //构造容器对象
services.AddScoped(); //注册
services.AddScoped();

//将Config对象绑在根节点configRoot 读取配置时, 要声明AddOptions
services.AddOptions()
    .Configure(e => configRoot.Bind(e))
    .Configure(e => configRoot.GetSection("proxy").Bind(e));

using (ServiceProvider sp = services.BuildServiceProvider()) //创建provider对象
{
    while (true)
    {
        await Task.Delay(1000);
        using (var scope = sp.CreateScope())
        {
            //新建CreateScope 可以自动刷新文本json的改变
            Console.WriteLine("-----------读取完整的TestController---Test方法实现----------------------------");
            var c = sp.GetRequiredService();
            c.Test();
            Console.WriteLine("-----------只读取Proxy的地址和端口号---Test方法实现----------------------------");
            var c2 = sp.GetRequiredService();
            c2.Test();
        }
    }




    
}





public class Proxy
{
    public string? Address  { get; set; }
    public string? Port { get; set; }
}

public class Config
{
    public string? Name { get; set; }
    public string? Age { get; set; }

    public Proxy? Proxy { get; set; }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/911219.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号