.net6 WebApi 之 Configuration

.net6 WebApi 使用 Configuration 获取 appsettings.json 中的内容,用法如下:

appsettings.json中的内容

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "xxx": "fff",
  "db": "123",
  "Tea": {
    "name": "张同学",
    "age": "18"
  }
}

1、获取单个字符串 xxx 的值

var x1 = builder.Configuration["xxx"];
var x2 = builder.Configuration.GetValue<string>("xxx");

2、获取Logging下面的Default的值,获取对象中的某个属性

var x = builder.Configuration["Logging:LogLevel:Default"];

3、获取对象的用法

var x3 = builder.Configuration.GetSection("Tea").Get<Student>();

还要先建一个Student类

    /// <summary>
    /// 学生类
    /// </summary>
    public class Student
    {
        public string name { get; set; }
        public string age { get; set; }
    }

 

posted @ 2022-10-14 10:06  幽冥狂_七  阅读(136)  评论(0编辑  收藏  举报