Checking MVC 6 Configuration

In the MVC 6 project, I have the following configuration file ...

{
  "ServiceSettings" :
  {
    "Setting1" : "Value"
  }
}

... and the next class ...

public class ServiceSettings
{
  public Setting1
  {
    get;

    set;
  }
}

In the ConfigureServicesclass method , StartupI added the following line of code ...

services.Configure<ServiceSettings>(Configuration.GetConfigurationSection("ServiceSettings"));

If a value is needed Setting1, how to check it? I could argue that the instance is IOptions<ServiceSettings>actually used, but if the value is Setting1necessary for the service to work, I would like to catch it as soon as possible, and not further downstream. The old object ConfigurationSectionallows you to specify rules that throw exceptions when configuration data was read if something was invalid.

+4
source share
3 answers

[Required] ServiceSettings Startup.ConfigureServices :

services.Configure<ServiceSettings>(settings =>
{
    ConfigurationBinder.Bind(Configuration.GetSection("ServiceSettings"), settings);

    EnforceRequiredStrings(settings);
})

Startup:

private static void EnforceRequiredStrings(object options)
{
    var properties = options.GetType().GetTypeInfo().DeclaredProperties.Where(p => p.PropertyType == typeof(string));
    var requiredProperties = properties.Where(p => p.CustomAttributes.Any(a => a.AttributeType == typeof(RequiredAttribute)));

    foreach (var property in requiredProperties)
    {
        if (string.IsNullOrEmpty((string)property.GetValue(options)))
            throw new ArgumentNullException(property.Name);
    }
}
+2

- :

services.Configure<ServiceSettings>(serviceSettings =>
{
    // bind the newed-up type with the data from the configuration section
    ConfigurationBinder.Bind(serviceSettings, Configuration.GetConfigurationSection(nameof(ServiceSettings)));

    // modify/validate these settings if you want to
});

// your settings should be available through DI now
+5

Starting netcore2.0, PostConfiguresuitable. This function also accepts a configuration delegate, but runs last, so everything is already configured.

// Configure and validate options
services.Configure<MyOptions>(Configuration.GetSection("section"));
services.PostConfigure<MyOptions>(myOptions => {
    // Take the fully configured myOptions and run validation checks...
    if (myOptions.Option1 == null) {
        throw new Exception("Option1 has to be specified");
    }
});
+1
source

Source: https://habr.com/ru/post/1609003/


All Articles