Reading Values From The Appsettings In .NET Core

In this article, I will explain how we can read the configuration setting from the appsettings.json file in .NET Core. To read the configuration setting we will use .AddOptions() method.

For example, below is my appsetting.json file and I want to read email settings from that file.

"EmailSettings": {
    "MailServer": "My-Server",
    "MailPort": 587,
    "SenderName": "Faisal Pathan",
    "Sender": "My Gmail",
    "Password": "My Password"
  }

Create a class with the same properties name as the appsettings.json file. I will use “EmailSettings” name as class name.

public class EmailSettings
{
    public string MailServer { get; set; }
    public int MailPort { get; set; }
    public string SenderName { get; set; }
    public string Sender { get; set; }
    public string Password { get; set; }
}

To use values open Startup.cs file and paste below code inside ConfigureServices() method.

services.AddOptions();

services.Configure<EmailSettings>(Configuration.GetSection("EmailSettings"));

Now wherever we want to use email settings just need to pass IOptions interface in the constructor as below.

private readonly EmailSettings _emailSettings;

public MyConstructor(IOptions<EmailSettings> emailSettings)
{
    _emailSettings = emailSettings.Value;
}

Now we can access all values using the _emailSettings variable. for example

var mail = new MailMessage()
{
    From = new MailAddress(_emailSettings.Sender, _emailSettings.SenderName),
    Subject = "My Subject",
    Body = "My Body",
    IsBodyHtml = true
};

I hope you guys found something useful. Please give your valuable feedback/comments/questions about this article. Please let me know how you like and understand this article and how I could improve it.

If you want to do the same thing with ASP.NET MVC you can vision the below link.

Reading A Key From The Web.Config

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories