在C#中,我们可以将appSettings中的某些设置绑定到class上,例如:
var connectionStrings = new ConnectionStrings();
var sectionConnectionString = Configuration.GetSection("ConnectionStrings");
在设置中,如下所示:
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
当我想绑定日志记录时,我需要调用另一个绑定:
Configuration.GetSection("Logging");
如何绑定整个appsettings文件?GetSection
空字符串不起作用:
Configuration.GetSection("");
你需要为你的配置添加一个类,然后你可以使用它(你不需要映射所有设置,只需映射所需的设置):
var configObject = Configuration.Get<ConfigObject>();
配置对象示例:
public class ConfigObject {
public Logging Logging { get; set; }
public string AllowedHosts { get; set; }
public ConnectionStrings ConnectionStrings { get; set; }
}
public class Logging {
public LogLevel LogLevel { get; set; }
}
public class LogLevel {
public string Default { get; set; }
}
public class ConnectionStrings {
public string ConnString1 { get; set; }
}
提示:
如果你不使用aspnetcore,则可能还需要包括以下NuGet软件包:Microsoft.Extensions.Configuration.Binder