Warm tip: This article is reproduced from serverfault.com, please click

configuration-C#将整个appSettings文件绑定到类

(configuration - C# bind whole appSettings file to class)

发布于 2020-11-30 10:38:35

在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("");
Questioner
Robert
Viewed
11
Maximilian Ast 2020-11-30 18:52:36

你需要为你的配置添加一个类,然后你可以使用它(你不需要映射所有设置,只需映射所需的设置):

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