Asp.net Core 获取json的配置,并映射到类

本文介绍了如何在ASP.NET Core 2.0项目中处理配置文件,特别是appsettings.json的读取。通过创建对应的类结构映射json内容,并利用依赖注入获取配置信息,例如只获取名为'test'的节点。在Startup.cs文件中,使用ConfigurationBuilder构建配置并注入到服务中,然后可以从服务提供者获取并使用配置。
摘要由CSDN通过智能技术生成
  1. 安装依赖包,由于我是用的是core 2.0 版本,安装的包版本可能和你的有区别
    在这里插入图片描述
  2. 定义实体类以及json文件添加

appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "test": {
    "name":"123"
  },
  "AllowedHosts": "*"
}

RootConfig类这个类的结构和json文件一样

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication.Config
{
    public class RootConfig
    {
        public Logging Logging { get; set; }

        public string AllowedHosts { get; set; }

        public test test { get; set; }
    }

    public class Logging
    {
        public LogLevel LogLevel { get; set; }
    }

    public class LogLevel
    {
        public string Default { get; set; }
    }

    public class test
    {
        public string name { get; set; }
    }
}

GetConfig类这里只是获取test这一个节点

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

namespace WebApplication.Config
{
    public class GetConfig
    {
        private readonly IOptionsSnapshot<test> _optionsSnapshot;

        public GetConfig(IOptionsSnapshot<test> optionsSnapshot)
        {
            _optionsSnapshot = optionsSnapshot;
        }

        public test getByName()
        {
            return _optionsSnapshot.Value;
        }
    }
}

startup.cs
只是获取test这个节点,要获取整个的json ,只需要将test替换成rootconfig,并删除configurationRoot.GetSection(“test”).Bind(x)
替换成configurationRoot.Bind(x)

services.AddScoped<GetConfig>();

            ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();

            configurationBuilder.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);


            IConfigurationRoot configurationRoot = configurationBuilder.Build();

            services.AddOptions().Configure<test>(x => configurationRoot.GetSection("test").Bind(x));

            var ss =  services.BuildServiceProvider().GetRequiredService<GetConfig>().getByName();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值