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