SylvainKrier
SylvainKrier

Reputation: 89

How to get section from a configuration file

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 ...

Upvotes: 0

Views: 1679

Answers (2)

Qing Guo
Qing Guo

Reputation: 9112

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

Try

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

Read this answer to know more

Result:

in appsetings.json:

"MailSettings": {
    "Mail": "[email protected]",
    "DisplayName": "aa",
    "Password": "123"
  }

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

Upvotes: 0

CodingMytra
CodingMytra

Reputation: 2600

try this.

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

Upvotes: 2

Related Questions