0

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

Jackdaw
  • 7,626
  • 5
  • 15
  • 33

2 Answers2

2

try this.

builder.Services.Configure<MailSettings>(builder.Configuration.GetSection("MailSettings"));
CodingMytra
  • 2,234
  • 1
  • 9
  • 21
0

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": "a@a.com",
    "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

Qing Guo
  • 6,041
  • 1
  • 2
  • 10