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

 

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