Home > Software design >  How to get section from a configuration file
How to get section from a configuration file

Time:06-25

I want to transfer data from appsettings.json to an instance of MailSettings at runtime :

Here's the model :

public class MailSettings
{
    public string Mail { get; set; }
    public string DisplayName { get; set; }
    public string Password { get; set; }
    public string Host { get; set; }
    public int Port { get; set; }
}

In program.cs, I try to configure the service with the following instruction:

    builder.Services.Configure<MailSettings>(Configuration.GetSection("MailSettings"));

But I have the following problem:

Compiler Error CS0120 : An object reference is required for the nonstatic field, method, or property Configuration.GetSection(string)

If someone has a solution ...

CodePudding user response:

try this.

builder.Services.Configure<MailSettings>(builder.Configuration.GetSection("MailSettings"));

CodePudding user response:

1. If you want to get section in program.cs

Try

var settings = builder.Configuration.GetSection("MailSettings").Get<MailSettings>();

Read enter image description here

2. If you want to get section in Controller/class

Try

builder.Services.Configure<MailSettings>(builder.Configuration.GetSection("MailSettings"));

HomeController:

 public class HomeController : Controller
    {
        public MailSettings MailSettings { get; }
        public HomeController(IOptions<MailSettings> smtpConfig)
        {
            MailSettings = smtpConfig.Value;
        }
    } 

Result:

enter image description here

  • Related