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

C# bind whole appSettings file to class

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

In C# we can bind some settings in appSettings to class, for example like that:

var connectionStrings = new ConnectionStrings();
var sectionConnectionString = Configuration.GetSection("ConnectionStrings");

In appsettings it looks like below:

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {

And when I want to bind Logging I need to call another bind:

Configuration.GetSection("Logging");

How can I bind whole appsettings file? GetSection with empty string doesn't work:

Configuration.GetSection("");
Questioner
Robert
Viewed
0
Maximilian Ast 2020-11-30 18:52:36

You need a Class for your config and afterwards you can use this (You do not need to map every setting, just the ones you need):

var configObject = Configuration.Get<ConfigObject>();

Example config object:

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

Hint: if you're not using aspnetcore you probably need to also include this NuGet package: Microsoft.Extensions.Configuration.Binder