c#读取配置

方法一:通过注入 IConfiguration 服务接口来读取

appsetting.json如下:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "Demo": {
    "key1": "1",
    "key2": "2",
    "key3": "3",
    "key4": "4",
    "Person": {
      "Name": "张三",
      "Address": "翻斗花园"
    }
  },
  "AllowedHosts": "*"
}

读取Demo中key3的值

var section = _configuration.GetSection("Demo");
var result = section.GetValue("key1","1");

读取Demo中Person中的address的值

var section = _configuration.GetSection("Demo:Person");
var result = section.GetValue("address", "");

方法二:通过注入 IConfiguration 服务接口来读取(推荐使用)

1.通过nuget为项目安装Microsoft.Extensions.Options以及Microsoft.Extensions.Configuration.Binder这两个Nuget包

2.新建配置项的模型类

appsetting.json如下:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "Demo": {
    "key1": "1",
    "key2": "2",
    "key3": "3",
    "key4": "4",
  },
  "AllowedHosts": "*"
}

比如说我们只需要读取Demo中的数据,新建Demo的模型类

public class DemoSettings
    {
        public string Key1 { get; set; }
        public string Key2 { get; set; }
        public string Key3 { get; set; }
        public string Key4 { get; set; }

    }

注册服务:

services.AddOptions().Configure<DemoSettings>(Configuration.GetSection("Demo"));

调用:

var smtp = _optionsSnapshotDemo.Value;
var result = smtp.Key3;            

 

posted @ 2022-09-27 13:57  ZerryLuo  阅读(190)  评论(0编辑  收藏  举报