What does GetSection and GetValue do differently when reading configuration values in ASP.NET Core?
Short answer
GetSection(key) returns an IConfigurationSection representing a subtree of configuration (useful for binding to an options class or enumerating children), returning an empty, non-null section even if the key doesn't exist (requires checking .Exists()).
Advertisement
AModel answer
GetSection(key) returns an IConfigurationSection representing a subtree of configuration (useful for binding to an options class or enumerating children), returning an empty, non-null section even if the key doesn't exist (requires checking .Exists()). GetValue<T>(key) directly reads and converts a single leaf value to the specified type, returning the type's default (or a specified fallback) if the key is missing, making it more convenient for simple scalar reads.
var section = configuration.GetSection("Smtp"); // returns a section, even if "Smtp" doesn't exist
if (!section.Exists()) Console.WriteLine("Smtp section missing");
var port = configuration.GetValue<int>("Smtp:Port", defaultValue: 587); // direct scalar read with fallbackReal-world example
A configuration validation utility uses GetSection(...).Exists() to check for optional feature configuration blocks before attempting to bind them, avoiding null reference exceptions on genuinely optional settings.
Likely follow-ups
- What does IConfigurationSection.Value return for a section with children instead of a leaf value?
- How does GetValue handle type conversion failures?
Related topics