Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IOptions Validation doesn't fire until I call validate method with property explicitly in Asp.Net Core 3

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

options-validation-in-aspnet-core

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?

like image 248
Rahul Avatar asked Dec 17 '25 10:12

Rahul


1 Answers

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.

like image 178
Tod Avatar answered Dec 20 '25 02:12

Tod