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

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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With