In .Net 6, there is a new extension method for this:
ConfigurationExtensions.GetRequiredSection()
Throws InvalidOperationException
if there is no section with the given key.
Further, if you're using the IOptions
pattern with AddOptions<TOptions>()
, the ValidateOnStart() extension method was also added in .Net 6 to be able to specify that validations should run at startup, instead of only running when the IOptions
instance is resolved.
With some questionable cleverness you can combine it with GetRequiredSection()
to make sure a section actually exist:
// Bind MyOptions, and ensure the section is actually defined.
services.AddOptions<MyOptions>()
.BindConfiguration(nameof(MyOptions))
.Validate<IConfiguration>((_, configuration)
=> configuration.GetRequiredSection(nameof(MyOptions)) is not null)
.ValidateOnStart();