NETCore 读取AppSetting配置文件参数

AppSetting.json

复制代码
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "Title": "Hello World!",
  "Message": "Hello World - AppSetting - 啊!",
  "ConnectionStrings": {
    "Mysql": "server=localhost;port=3306;userid=root;pwd=123456;database=testefdb",
    "MsSql": "Data Source=.;Initial Catalog=testefdb;User Id=root;Password=123456;"
  }
}
appsetting.json
复制代码

jsconfig.json

复制代码
{
  "Name": "Joker",
  "Sex": "Man",
  "Describe": "描述",
  "Message": "Hello World - JsConfig - 啊!"
}
jsconfig.json
复制代码

构造函数注入参数

public Microsoft.Extensions.Configuration.IConfiguration Configuration { get; }

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

获取配置文件参数

1.获取指定key的值

var title = Configuration["Title"];
var mysql = Configuration["ConnectionStrings:Mysql"];

2.绑定配置模型对象

复制代码
            // 获取所有配置
            var appSetting = new MyAppSetting();
            Configuration.Bind(appSetting);
            var loggerDefault = appSetting.Logging.LogLevel.Default;

            // 获取指定节点配置
            var connectionstrings = new Connectionstrings();
            Configuration.GetSection("ConnectionStrings").Bind(connectionstrings);
            var mssql = connectionstrings.MsSql;
复制代码

3.注册配置选项的服务

3.1.在 Startup/ConfigureServices 注册配置选项服务

            // 注册配置选项服务: Microsoft.Extensions.Hosting
            services.Configure<MyAppSetting>(Configuration);
            // 注册 自定义配置信息
            var config = new ConfigurationBuilder().AddJsonFile("jsconfig.json", true, true).Build();
            var name = config["Name"];
            services.Configure<MyJsConfig>(config);

3.2.在 Startup/Configure 获取配置

        public void Configure(IOptions<MyAppSetting> appSettingOptions, IOptionsSnapshot<MyJsConfig> myJsConfigoptions)
        {
            // 读取 配置信息【appsettings.json】
            var loggerMicrosoft = appSettingOptions.Value.Logging.LogLevel.Microsoft;

            // 读取 自定义配置信息【jsconfig.json】
            var describe = myJsConfigoptions.Value.Describe;
        }

*注:

1.在 Startup/ConfigureServices 通过 AddJsonFile 注册自定义配置信息,使用IOptionsSnapshot【站点启动后,每次获取到的值都是配置文件里的最新值】没有效果,需要在 Program/CreateHostBuilder 中进行配置【有知道的大佬求解释】

复制代码
        public static IHostBuilder CreateHostBuilder(string[] args)
        {
            // 创建默认Builder,完成各种基础配置: Host.CreateDefaultBuilder 已注册 appsetting.json
            IHostBuilder hostBuild = Host.CreateDefaultBuilder(args);
            // 配置默认WebHost
            hostBuild.ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
            hostBuild.ConfigureAppConfiguration(configBuilder =>
            {
                // 注册 自定义配置信息,reloadOnChange:如果文件更改,是否应重新加载配置(Microsoft.Extensions.Configuration.Json)
                configBuilder.AddJsonFile("jsconfig.json", true, reloadOnChange: true);
            });
            return hostBuild;
        }
复制代码

2.appsetting.jsonjsconfig.json 两个配置文件会同时生效,同名的值后者优先【jsconfig.json

3.早期Core版本获取动态配置需要手动指定 reloadOnchange = true,目前3.1已默认配置,只需要使用 Microsoft.Extensions.Options.IOptionsSnapshot 就可以

 

posted @   Robot-Blog  阅读(1152)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示