.NET Core

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

Faisal Pathan

Faisal Pathan is a founder of TheCodeHubs, .NET Project Manager/Team Leader, and C# Corner MVP. He has extensive experience with designing and developing enterprise-scale applications. He has good skills in ASP.NET C#, ASP.NET Core, ASP.NET MVC, AngularJS, Angular, React, NodeJS, Amazon S3, Web API, EPPlus, Amazon MWS, eBay Integration, SQL, Entity Framework, JavaScript, eCommerce Integration like Walmart, Tanga, Newegg, Group-on Store, etc. and Windows services.

Share
Published by
Faisal Pathan

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

3 years ago