首页 > 其他分享 >NET Core 6.0之读取配置文件

NET Core 6.0之读取配置文件

时间:2023-09-29 23:33:57浏览次数:38  
标签:Core string 配置文件 builder Wechat WechatConfiguration NET Configuration public

ASP.NET Core默认加载顺序是appsettings.json->appsettings.Environment.json,它会根据当前的运行环境去加载不同的配置文件,最后appsettings.Environment.json 值将替代 appsettings.json 中的值,如果没有多个值,则取默认值。

在开始之前,我们先在appsettings.json中新增一些配置信息

"Wechat": {
    "AppId": "wx26c607c55f31745e",
    "AppSecret": "e7da82499266ca3fdf85290f68f8fd3a"
  }

一、简单读取配置

1、在Program.cs中尝试读取配置文件中AppId和AppSecret的值,可以用WebApplicationBuilder里面的Configuration属性来读取,取配置内容的方式有很多,比如:

string appId = builder.Configuration.GetSection("Wechat")["AppId"];
string appSecret = builder.Configuration.GetSection("Wechat")["AppSecret"];

或者

string appId1 = builder.Configuration["Wechat:AppId"];
string appSecret1 = builder.Configuration["Wechat:AppSecret"];

或者更深的层级取消

    string appId1 =builder.Configuration["AppConfig:Wechat:Ap"]

 string appSecret1 =builder.Configuration["AppConfig:Wechat:AppSecret"]

2、在非Program.cs里面读取配置,则需要注入IConfiguration实例,其他操作方式便和前面的一致,新建一个Controller

[Route("api/[controller]")]
[ApiController]
public class ConfigurationController : ControllerBase
{
    private readonly IConfiguration Configuration;

    public ConfigurationController(IConfiguration configuration) {
        Configuration = configuration;
    }

    [HttpGet]
    public string ReadConfig()
    {
        return Configuration["Wechat:AppId"];
    }
}

直接访问api/Configuration,便能返回配置文件中的AppId信息,

3、配置绑定到实体

如果配置文件比较复杂,用前面的方式一个个的去取值,确实有些繁琐,所以,需要更高端的操作,直接把配置内容装载到实体类中,新建一个名为WechatConfiguration的类,里面加入与配置文件对应的属性

public class WechatConfiguration
{
    public const string KEY = "Wechat";

    public string AppId { get; set; } = String.Empty;
    public string AppSecret { get; set; } = String.Empty;
}

这里,需要使用的IConfiguration的GetSection方法来获取指定节点的内容,然后使用Get将内容序列化为对象,看例子

Configuration.GetSection(WechatConfiguration.KEY).Get<WechatConfiguration>(); 

除了,使用Get取值,还可使用Bind方法,将值绑定到对象上

WechatConfiguration wechatConfiguration = new WechatConfiguration();
Configuration.GetSection(WechatConfiguration.KEY).Bind(wechatConfiguration);

这两种方式都能获取到配置文件修改后的内容,除了上面两种方式获取配置内容外,还可以使用直接将配置对象注入到容器中,

builder.Services.Configure(builder.Configuration.GetSection(WechatConfiguration.KEY));

然后在需要使用的类中注入IOptions,通过其Value属性来获取配置类对象

public class ConfigurationController : ControllerBase
{
    private readonly IConfiguration Configuration;
    private readonly WechatConfiguration wechat;

    public ConfigurationController(IConfiguration configuration, IOptions options)
    {
        Configuration = configuration;
        wechat = options.Value;
    }
}

如果配置类过多,那么在Program.cs便会显得杂乱臃肿,所以,可以将其移动到扩展方法以注册服务,这里新建一个扩展类

ConfigServiceCollectionExtensions,将前面的代码移动到该类中

public static class ConfigServiceCollectionExtensions
{
    public static IServiceCollection AddConfig(this IServiceCollection services, IConfiguration config)
    {
        services.Configure(config.GetSection(WechatConfiguration.KEY));
        return services;
    }
}

然后在Program.cs中添加引用即可

builder.Services.AddConfig(builder.Configuration);

标签:Core,string,配置文件,builder,Wechat,WechatConfiguration,NET,Configuration,public
From: https://www.cnblogs.com/lc5259/p/17737521.html

相关文章

  • java springboot项目,mybatisplus,import com.baomidou.mybatisplus.core.mapper.BaseMa
    <dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.1.2</version><!--用版本2.1.9就不行,UserMapper里BaseMapper爆红--></dependency>我的结果是,......
  • 进化算法中的遗传算法(Genetic Algorithms)
    进化算法中的遗传算法(GeneticAlgorithms)引言进化算法是一类基于自然进化原理的优化算法,通过模拟生物进化过程中的选择、交叉和变异等操作,来求解复杂问题。遗传算法(GeneticAlgorithms)是进化算法中最为经典和常用的一种方法。本文将介绍遗传算法的基本原理、核心操作和应用领域,以及......
  • Windows Server 2008 + IIS 7+ ASP.NET 支持10万并发请求
    调整IIS7应用程序池队列长度由原来的默认1000改为65535。InternetInformationServices(IIS)管理器>应用程序池>当前需要修改的网站所对应的应用程序池>高级设置队列长度:65535@echooffsetnewQueueLength=65535REM获取IIS安装路径for/f"tokens=2delims==......
  • Aveva Marine VBNET 编程系列-新建图纸,创建文字
    根据MarApi,创建图形文件,新建文字ImportsAveva.ApplicationFramework.PresentationImportsAveva.Marine.Drafting'marAPI.dllPublicClass绘图控制<MyAmFunctionAtt(NameOf(绘图控制),NameOf(新建图纸))>PublicSub新建图纸(wmAsWindowManager)Di......
  • asp .net core Exceptionless日志操作
    exceptionless官网使用说明安装Nuget包添加引用usingExceptionless;usingExceptionless.Logging;初始化-秘钥-请求地址//构造函数初始化日志参数(日志系统地址,项目模块)publicDefaultController(){if(string.IsNullOrWhiteSpace(ExceptionlessClient.Default.Config......
  • .NET应用如何防止被反编译
    前言前段时间分享了两篇关于.NET反编译相关的文章,然后文章留言区就有小伙伴提问:如何防止被反编译?因此本篇文章我们就来讲讲.NET应用如何防止被反编译。.NET反编译相关的文章可以看如下文章:4款免费且实用的.NET反编译工具.NET反编译神器ILSpy怎么用?.NET应用如何防止被反编译......
  • Aveva Marine VBNET 编程系列-修改程序快捷键
    修改HullDesign程序的主题以及菜单项的快捷键 引用的dll文件下面的是代码和快捷键配置文件:https://files.cnblogs.com/files/NanShengBlogs/AMShortCut.HullDesign.zip?t=1695908179&download=trueImportsAveva.ApplicationFramework.PresentationImportsAveva.Applic......
  • .net 7 智能提示汉化翻译中文版 dotnet 7 来帮助我们使用 asp.net core开发的时候,一些
    .net7智能提示汉化翻译中文版dotnet7来帮助我们使用asp.netcore开发的时候,一些参数或者方法可以更好的使用!   纯手工,使用必应翻译翻译的,翻译质量参次不齐。妄大家海涵!不懂如何使用可以联系QQ:11392301......
  • 02. Kubeadm部署Kubernetes集群
    目录1、前言2、Kubernetes部署方式3、kubeadmin部署3.1、关闭防火墙3.2、配置阿里云Kubernetes源3.3、安装kubeadm,kubelet,kubectl3.4、初始化master节点3.5、master节点配置kubectl命令行工具3.6、master节点下载flannel网络配置文件3.7、node1和node2节点加入Kubernetes集群3.8、......
  • 楼宇暖通专用工业路由器支持BACnet协议
    钡铼4G工业路由器支持BACnetMS/TP协议。BACnetMS/TP协议是一种用于工业自动化的开放式通信协议,被广泛应用于楼宇自动化、照明控制、能源管理等领域。通过钡铼4G工业路由器的支持,可以使设备间实现高速、可靠的数据传输,提高自动化水平。钡铼4G工业路由器采用高性能的硬件配置,支持多......