.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; }
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章