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>();
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: