Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 301
gottacodeemall Avatar asked Dec 06 '25 19:12

gottacodeemall


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

like image 194
edo.n Avatar answered Dec 08 '25 07:12

edo.n



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!