.Net 6读取json配置文件

使用.Net 6

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net6.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="6.0.3" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Abstractions" Version="6.0.3" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="6.0.3" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.3">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.Extensions.Configuration" Version="6.0.1" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="6.0.0" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0" />
    <PackageReference Include="Microsoft.Extensions.Options" Version="6.0.0" />
    <PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
    <PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="6.0.1" />
  </ItemGroup>

  <ItemGroup>
    <None Update="config.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>
  </ItemGroup>

</Project>


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

{
  "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<Proxy>();
Console.WriteLine($"IP地址是:{ proxy.Address},端口号是{proxy.Port}");


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

Config config = configRoot.Get<Config>();

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:\Csharp\ConfigTestDemon\ConfigTestDemon\bin\Debug\net6.0\ConfigTestDemon.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<Config> optConfig;

        private IOptionsSnapshot<Config> optConfig;

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



        public TestController(IOptionsSnapshot<Config> 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<Proxy> optProxy;

        public OnlyProxy(IOptionsSnapshot<Proxy> 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<TestController>(); //注册
services.AddScoped<OnlyProxy>();

//将Config对象绑在根节点configRoot 读取配置时, 要声明AddOptions
services.AddOptions()
    .Configure<Config>(e => configRoot.Bind(e))
    .Configure<Proxy>(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<TestController>();
            c.Test();
            Console.WriteLine("-----------只读取Proxy的地址和端口号---Test方法实现----------------------------");
            var c2 = sp.GetRequiredService<OnlyProxy>();
            c2.Test();
        }
    }




    /*
     * 结果:
     --------------使用DI依赖注入----------------------------
    -----------读取完整的TestController---Test方法实现----------------------------
    18
    ---------------
    aa
    -----------只读取Proxy的地址和端口号---Test方法实现----------------------------
    用OnlyProxy实现IP为aa,端口号为:8080
     */
}





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; }
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

潘诺西亚的火山

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值