Recently i was using IOptions interface to read configuration in Asp.net core project and i found that my code doesn't show exception page until i call "validate" method explicitly with required property as you can see in below code.
appsettings.json
"DashboardSettings": {
"Header": {
"Title": "Seguro De Coche"//,
//"SearchBoxEnabled": true
}
},
DashboardSetting.cs
public class DashboardSettings
{
public HeaderSettings Header { get; set; }
}
public class HeaderSettings
{
public string Title { get; set; }
[Required]
public bool SearchEnabled { get; set; }
}
Startup.cs
services.AddOptions<DashboardSettings>().
Bind(configuration.GetSection("DashboardSettings")).
ValidateDataAnnotations();
In above case, "SearchEnabled" property required validation doesn't fire. and when i call validate methods explicitly with property, it fires. (see code below with validation method)
services.AddOptions<DashboardSettings>().
Bind(configuration.GetSection("DashboardSettings")).
ValidateDataAnnotations().
Validate(v =>
{
return v.Header.SearchEnabled;
});

so my question is, if my strongly type would have multiple configuration properties, then would i use all properties of class for validating them? If it is, it doesn't seem a good idea to me. Any suggestion on this please?
I don't know if this was an option back in .net core 3 but in .net core 6 you have to call
.ValidateOnStart()
on the optionsbuilder returned from AddOptions<>()
Otherwise, validation is called when the object is retrieved for the first time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With