Config Values are null when trying to access them using GetSection in startup file.(IOptions-config retrieval)

Viewed 1140

I'm not able to receive the config values from appsettings file in .NET Core.

appsettings.json:

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "PortedConfig": {
    "ConfigTableAccess": "ConfigTableConnectionString",
    "ConfigTableName": "Config"
  }
}

startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddOptions();
    var config = Configuration;
    var settings = Configuration.GetSection("PortedConfig").Get<PortedConfig>();
    services.Configure<PortedConfig>(options => Configuration.GetSection("PortedConfig").Bind(options));
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    services.AddScoped<IEncryptManager, EncryptManager>()
            .AddScoped<IDecryptManager, DecryptManager>();
}

PortedConfig.cs:

public class PortedConfig
{
    public string ConfigTableAccess;
    public string ConfigTableName;
}

In startup.cs, at runtime the configuration is getting populated but when I use GetSection the values are null as shown in images below:

Screenshot of Configuration Screenshot of Configuration

As you can see in images above ConfigTableAccess and ConfigTableName are null in settings variable.

1 Answers

Change the fields to properties and don't forget a public setter.

public class PortedConfig
{
    public string ConfigTableAccess { get; set; }
    public string ConfigTableName { get; set; }
}

Related