Home > Back-end >  .Net 6 config.GetSection() does not act as expected
.Net 6 config.GetSection() does not act as expected

Time:04-02

I'm trying to get configuration section in .net 6 project, the problem I came across is that GetSection() doesn't act as expected, it doesn't return the section, it's just null. Here is some code snippet:

public static IServiceCollection AddServices(this IServiceCollection services, IConfiguration config)
{
    var e = config["EmailConfig"];
    var s = config.GetSection("EmailConfig:Server");
    IConfigurationSection emailConfigSection = config.GetSection(EmailConfig.Name);
    services.Configure<EmailConfig>(emailConfigSection);

    return services;
}

EmailConfig.Name is a constant and equals to "EmailConfig"

variable values look following way e = null, s = "server" and emailConfigSection = null, so what's the reason? Why can't I get full sections

appsettings.json if needed:

{
 "EmailConfig": {
    "Server": "server",
    "Port": 587,
    "UseSSL": true,
    "Username": "name",
    "Password": "password",
    "DefaultSender": "sender"
  }
}

configuration while debugging

CodePudding user response:

You need to do:

var e = config.GetSection("EmailConfig");

not

var e = config["EmailConfig"];

OR Here is a more detailed approach to get the result you are after.

//this gets called at runtime Startup.cs

Public Class Startup 
{

   private readonly IConfiguration _configuration;

   public Startup(IConfiguration configuration)
   {
      _configuration = configuration;
   }

   public void ConfigureServices(IServiceCollection services)
   {
       //set up config
       services.AddOptions();
       services.Configure<EmailConfig> (_configuration.GetSection("EmailConfig"));
   }

}

We can create a Model to access our config later(EmailConfig)

    public class EmailConfig
    {
        public string Server { get; set; }
        public int Port { get; set; }
        public bool UseSSL { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
        public string DefaultSender { get; set; }
    }

Getting your config value later on: Let's say we need to access the Server

Public class TestApi
{
     private readonly EmailConfig _emailConfig
     
     public TestApi(IOptions<EmailConfig) emailConfig)
     {
        _emailConfig = emailConfig.Value
     }

     public string ReturnServer
     {
        var serverName = _emailConfig.Server;
        return serverName;
     }
}

CodePudding user response:

If you have a model class defined for EmailConfig, use below code.

IConfigurationSection emailConfigSection = config.GetSection(EmailConfig.Name).Get<EmailConfig>();

else you need to get key value from its property name like below:

IConfigurationSection emailConfigSection = config.GetSection(EmailConfig.Name);
var server = emailConfigSection["Server"];
var port = emailConfigSection["Port"];
....
  • Related