iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > ASP.NET >浅析.netcore中的Configuration具体使用
  • 222
分享到

浅析.netcore中的Configuration具体使用

2024-04-02 19:04:59 222人浏览 八月长安
摘要

目录添加其他配置文件源码解读:读取层级配置项选项模式获取配置项命名选项的使用不管是.net还是.netcore项目,我们都少不了要读取配置文件,在.net中项目,配置一般就存放在WE

不管是.net还是.netcore项目,我们都少不了要读取配置文件,在.net中项目,配置一般就存放在WEB.config中,但是在.netcore中我们新建的项目根本就看不到web.config,取而代之的是appsetting.JSON

新建一个webapi项目,可以在startup中看到一个IConfiguration,通过框架自带的ioc使用构造函数进行实例化,在IConfiguration中我们发现直接就可以读取到appsetting.json中的配置项了,如果在控制器中需要读取配置,也是直接通过构造

函数就可以实例化IConfiguration对象进行配置的读取。下面我们试一下运行的效果,在appsetting.json添加一个配置项,在action中可以进行访问。

添加其他配置文件

那我们的配置项是不是只能写在appsetting.json中呢?当然不是,下面我们看看如何添加其他的文件到配置项中,根据官网教程,我们可以使用ConfigureAppConfiguration实现。

首先我们在项目的根目录新建一个config.json,然后在其中随意添加几个配置,然后在program.cs中添加高亮显示的部分,这样很简单的就将我们新增的json文件中的配置加进来了,然后在程序中就可以使用IConfiguration进行访问config.json中的配置项了。


public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration(configure => {               
                configure.AddJsonFile("config.json");  //无法热修改

            })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

但是这个无法在配置项修改后读取到最新的数据,我们可以调用重载方法configure.AddJsonFile("config.json",true,reloadOnChange:true)实现热更新。

除了添加json文件外,我们还可以使用AddXmlFile添加xml文件,使用AddInMemoryCollection添加内存配置


public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((context,configure) => {
            Dictionary<string, string> memoryConfig = new Dictionary<string, string>();
            memoryConfig.Add("memoryKey1", "m1");
            memoryConfig.Add("memoryKey2", "m2");
    
            configure.AddInMemoryCollection(memoryConfig);
    
        })
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });

源码解读:

在自动生成的项目中,我们没有配置过如何获取配置文件,那.netcore框架是怎么知道要appsetting.json配置文件的呢?我们通过查看源码我们就可以明白其中的道理。


Host.CreateDefaultBuilder(args)    
    .ConfigureWebHostDefaults(webBuilder =>
    {
        webBuilder.UseStartup<Startup>();
    });


//CreateDefaultBuilder源码
public static IHostBuilder CreateDefaultBuilder(string[] args)
{
    var builder = new HostBuilder();

    builder.UseContentRoot(Directory.GetCurrentDirectory());
    builder.ConfigureHostConfiguration(config =>
    {
        config.AddEnvironmentVariables(prefix: "dotnet_");
        if (args != null)
        {
            config.AddCommandLine(args);
        }
    });

    builder.ConfigureAppConfiguration((hostinGContext, config) =>
    {
        var env = hostingContext.HostingEnvironment;

        config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
              .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);

        if (env.IsDevelopment() && !string.IsNullOrEmpty(env.ApplicationName))
        {
            var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
            if (appAssembly != null)
            {
                config.AddUserSecrets(appAssembly, optional: true);
            }
        }

        config.AddEnvironmentVariables();

        if (args != null)
        {
            config.AddCommandLine(args);
        }
    });
    
    ....

    return builder;
}

怎么样?是不是很有意思,在源码中我们看到在Program中构建host的时候就会调用ConfigureAppConfiguration对应用进行配置,会读取appsetting.json文件,并且会根据环境变量加载不同环境的appsetting,同时还可以看到应用不仅添加了

appsetting的配置,而且添加了从环境变量、命令行传入参数的支持,对于AddUserSecrets支持读取用户机密文件中的配置,这个在存储用户机密配置的时候会用到。

那为什么我们可以通过再次调用ConfigureAppConfiguration去追加配置信息,而不是覆盖呢?我们同样可以在源码里面找到答案。


public static void Main(string[] args)
{
    CreateHostBuilder(args).Build().Run();
}
//以下为部分源码
private List<Action<HostBuilderContext, IConfigurationBuilder>> _configureAppConfigActions = new List<Action<HostBuilderContext, IConfigurationBuilder>>();private IConfiguration _appConfiguration;

public IHostBuilder ConfigureAppConfiguration(Action<HostBuilderContext, IConfigurationBuilder> configureDelegate)
{
    _configureAppConfigActions.Add(configureDelegate ?? throw new ArgumentNullException(nameof(configureDelegate)));
    return this;
}


public IHost Build()
{
    ...

    BuildAppConfiguration();

    ...
}

private void BuildAppConfiguration()
{
    var configBuilder = new ConfigurationBuilder()
        .SetBasePath(_hostingEnvironment.ContentRootPath)
        .AddConfiguration(_hostConfiguration, shouldDisposeConfiguration: true);

    foreach (var buildAction in _configureAppConfigActions)
    {
        buildAction(_hostBuilderContext, configBuilder);
    }
    _appConfiguration = configBuilder.Build();
    _hostBuilderContext.Configuration = _appConfiguration;
}

框架声明了一个List<Action<HostBuilderContext, IConfigurationBuilder>>,我们每次调用ConfigureAppConfiguration都是往这个集合中添加元素,等到Main函数调用Build的时候会触发ConfigurationBuilder,将集合中的所有元素进行循环追加

到ConfigurationBuilder,最后就形成了我们使用的IConfiguration,这样一看对于.netcore中IConfiguration是怎么来的就很清楚了。

读取层级配置项

如果需要读取配置文件中某个层级的配置应该怎么做呢?也很简单,使用IConfiguration["key:childKey..."]

比如有这样一段配置:


"config_key2": {
    "config_key2_1": "config_key2_1",
    "config_key2_2": "config_key2_2"
  }

可以使用IConfiguration["config_key2:config_key2_1"]来获取到config_key2_1的配置项,如果config_key2_1下还有子配置项childkey,依然可以继续使用:childkey来获取

选项模式获取配置项

选项模式使用类来提供对相关配置节的强类型访问,将配置文件中的配置项转化为POCO模型,可为开发人员编写代码提供更好的便利和易读性

我们添加这样一段配置:


"Student": {
    "Sno": "SNO",
    "Sname": "SNAME",
    "Sage": 18,
    "ID": "001"
  }

接下来我们定义一个Student的Model类


public class Student
{
    private string _id;
    public const string Name = "Student";
    private string ID { get; set; }
    public string Sno { get; set; }
    public string Sname { get; set; }
    public int Sage { get; set; }
}

可以使用多种方式来进行绑定:

1、使用Bind方式绑定


Student student = new Student();
_configuration.GetSection(Student.Name).Bind(student);

2、使用Get方式绑定


var student1 = _configuration.GetSection(Student.Name).Get<Student>(binderOptions=> {
  binderOptions.BindNonPublicProperties = true;
});

Get方式和Bind方式都支持添加一个Action<BinderOptions>的重载,通过这个我们配置绑定时的一些配置,比如非公共属性是否绑定(默认是不绑定的),但是Get比BInd使用稍微方便一些,如果需要绑定集合也是一样的道理,将Student

替换成List<Student>。

3、全局方式绑定

前两种方式只能在局部生效,要想做一次配置绑定,任何地方都生效可用,我们可以使用全局绑定的方式,全局绑定在Startup.cs中定义


services.Configure<Student>(Configuration.GetSection(Student.Name));

此方式会使用选项模式进行配置绑定,并且会注入到IOC中,在需要使用的地方可以在构造函数中进行实例化


private readonly ILogger<WeatherForecastController> _logger;
private readonly IConfiguration _configuration;
private readonly Student _student;

public WeatherForecastController(ILogger<WeatherForecastController> logger, IConfiguration configuration, IOptions<Student> student)
{
    _logger = logger;
    _configuration = configuration;
    _student = student.Value;
}

命名选项的使用

对于不同的配置节,包含的配置项一样时,我们在使用选项绑定的时候无需定义和注入两个类,可以在绑定时指定名称,比如下面的配置:


"Root": {
  "child1": {
    "child_1": "child1_1",
    "child_2": "child1_2"
  },
  "child2": {
    "child_1": "child2_1",
    "child_2": "child2_2"
  }
}public class Root{  public string child_1{get;set;}  public string child_2{get;set;}}

services.Configure<Root>("Child1",Configuration.GetSection("Root:child1"));
services.Configure<Root>("Child2", Configuration.GetSection("Root:child2"));

private readonly ILogger<WeatherForecastController> _logger;
private readonly IConfiguration _configuration;
private readonly Student _student;
private readonly Root _child1;
private readonly Root _child2;

public WeatherForecastController(ILogger<WeatherForecastController> logger, IConfiguration configuration, IOptions<Student> student,IOptionsSnapshot<Root> root)
{
    _logger = logger;
    _configuration = configuration;
    _student = student.Value;
    _child1 = root.Get("Child1");
    _child2 = root.Get("Child2");
}

到此这篇关于浅析.netcore中的Configuration具体使用的文章就介绍到这了,更多相关.net core Configuration内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: 浅析.netcore中的Configuration具体使用

本文链接: https://www.lsjlt.com/news/160876.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • 浅析.netcore中的Configuration具体使用
    目录添加其他配置文件源码解读:读取层级配置项选项模式获取配置项命名选项的使用不管是.net还是.netcore项目,我们都少不了要读取配置文件,在.net中项目,配置一般就存放在we...
    99+
    2024-04-02
  • 浅谈Vue3中watchEffect的具体用法
    前言 watchEffect,它立即执行传入的一个函数,同时响应式追踪其依赖,并在其依赖变更时重新运行该函数。 换句话说:watchEffect相当于将watch 的依赖源...
    99+
    2024-04-02
  • 浅析Java中并发工具类的使用
    目录CountDownLatch概述案例原理源码分析CyclicBarrier概述案例源码分析与CountDonwLatch的区别Semaphore概述使用场景案例原理Exchang...
    99+
    2022-12-08
    Java并发工具类使用 Java并发工具类 Java并发
  • 解析.netcore项目中IStartupFilter使用教程
    背景: netcore项目中有些服务是在通过中间件来通信的,比如orleans组件。它里面服务和客户端会指定网关和端口,我们只需要开放客户端给外界,服务端关闭端口。相当于去掉host...
    99+
    2024-04-02
  • React中useRef的具体使用
    相信有过React使用经验的人对ref都会熟悉,它可以用来获取组件实例对象或者是DOM对象。 而useRef这个hooks函数,除了传统的用法之外,它还可以“跨渲染周期”保存数据。 ...
    99+
    2024-04-02
  • python中pywifi的具体使用
    目录写在前面pywifi常量接口wifi连接代码写在前面 无线AP(Access Point):即无线接入点 python的wifi管理模块叫pywifi 安装 pip instal...
    99+
    2023-03-06
    python pywifi
  • Golang中Model的具体使用
    目录导语使用之前的准备开始使用发布版本引用自己封装的包修改版本导语 我们都知道在Golang中我们一般都是设置GOPATH目录,这个目录主要存放我们的第三方包,这个方式一直不是很方便...
    99+
    2023-05-14
    Golang Model使用 Golang Model
  • java中Thread.sleep()的具体使用
    目录sleep功能介绍:sleep Thread.sleep()被用来暂停当前线程的执行,会通知线程调度器把当前线程在指定的时间周期内置为wait状态。当wait时间结束,线程状态重...
    99+
    2023-05-17
    java Thread.sleep
  • numpy中nan_to_num的具体使用
    在Numpy中NaN值一般出现在数据清洗前,出现这个值说明这个数据是缺失的 在有些时候我们会选择直接删除这些数据,但有些时候这些数据是不能删除的,这个时候我们就需要使用一些方法将np...
    99+
    2024-04-02
  • pandas中df.rename()的具体使用
    df.rename()用于更改行列的标签,即行列的索引。可以传入一个字典或者一个函数。在数据预处理中,比较常用。 官方文档: DataFrame.rename(self, mappe...
    99+
    2024-04-02
  • django中websocket的具体使用
    websocket是一种持久化的协议,HTTP协议是一种无状态的协议,在特定场合我们需要使用长连接,做数据的实时更新,这种情况下我们就可以使用websocket做持久连接。http与...
    99+
    2024-04-02
  • java中的DateTime的具体使用
    目录1.初始化时间2.按格式输出时间(将DateTime格式转换为字符串)3.将字符串转换为DateTime格式4.取得当前时间5.计算两个日期间隔的天数6.增加日期7.减少日期8....
    99+
    2024-04-02
  • C#中{get;set;}的具体使用
    在C#程序中经常会看到set,get的配套使用,很多人不知道它的用途。我就在这向大家讲讲,也加深一下自己的印象。 //这里有两个类 public class person1 { ...
    99+
    2023-02-06
    C# {get;set;} C# GET SET
  • Quartz.NET的具体使用
    目录一、什么是Quartz.NET?二、Quartz.NET可以做什么?三、ASP.NET Core如何使用Quartz.NET?四、Quartz的cron表达式一、什么是Quart...
    99+
    2024-04-02
  • JavaScheduledExecutorService的具体使用
    目录1. 延迟不循环任务schedule方法2. 延迟且循环cheduleAtFixedRate方法3. 严格按照一定时间间隔执行``ScheduledExecutorService...
    99+
    2023-05-19
    ScheduledExecutorService
  • QtQFrame的具体使用
    目录1.概述2.常用数据接口3.示例1.概述 void setFrameShape(Shape) QFrame继承QWidget,QFrame类是具有框架的小部件的基类,例如QLab...
    99+
    2024-04-02
  • Vue中this.$nextTick()的具体使用
    目录1、官网说法2、DOM 更新3、获取更新后的 DOM4、小结:this.$nextTick()的使用场景1、官网说法 在下次 DOM 更新循环结束之后执行延迟回调。在修改数据之后...
    99+
    2023-02-06
    Vue this.$nextTick()
  • python__add__()的具体使用
    __add__(),  同一个类,两个对象相加的实现逻辑,重写 + class Myclass(object): def __init__(self,value):...
    99+
    2023-02-27
    python __add__()使用 python __add__
  • pythonhttpx的具体使用
    目录什么是 Httpx安装 Httpx发送 HTTP 请求发送异步 HTTP 请求设置请求标头设置请求参数发送请求体发送 JSON 数据设置超时错误处理证书验证使用代理上传文件使用 ...
    99+
    2023-05-14
    python httpx
  • np.unique()的具体使用
    目录一、np.unique() 介绍二、np.unique() 原型三、实例参考链接一、np.unique() 介绍 对于一维数组或者列表,np.unique() 函数 去除其中重复...
    99+
    2023-03-14
    np.unique()使用 np.unique()
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作