ASP.NET CORE读取配置文件

appsetting.josn文件:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=db;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "Logging": {
    //Debug中最低输出级别Information
    "Debug": {
      "LogLevel": {
        "Default": "Trace"
      }
    },
    //Console中最低输出级别Trace
    "Console": {
      "LogLevel": {
        "Default": "Information"
      }
    },
    "LogLevel": {
      "Default": "Trace" //日志最低级别
    }
  },
  "AllowedHosts": "*"
}

 

读取:

public IActionResult Config()
{
    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    //获取根目录
    configurationBuilder.SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json");
    //构建configurationBuilder对象
    var configuration = configurationBuilder.Build();
    //获取字符串
    var conectString = configuration.GetConnectionString("DefaultConnection");
    //获取AllowedHosts
    var AllowedHosts = configuration["AllowedHosts"];
    //获取Loggin下的Default
    var Default = configuration["Logging:Console:LogLevel:Default"];

    return Content(Default);
}

 

appsetting.josn中的json数据

"Student": [
    {
      "name": "张三",
      "age": "36",
      "hobby": [
        {
          "ballGame": "Basketball"
        },
        {
          "skill": "sing"
        }
      ]
    },
    {
      "name": "李四",
      "age": "23"
    }
  ]

读取:

 //获取张三的年龄
var name= configuration["Student:0:age"];

//获取张三唱歌的爱好
var sing = configuration["Student:0:hobby:1:skill"];

 

上一篇:vuecli4创建项目失败command failed: npm install --loglevel error


下一篇:celery+django的定时任务设置 - 最佳实践 - 在django管理后台配置定时任务