Ads

Web API 7 : Read the value from appsettings.json file

 Hello All,

Welcome back, In this article we will discuss about accessing the appsetting.json file value(key value pair) in any controller action method.

Recap...

We have created the API in the article Web API Part 1 - ASP .NET Core Web API Using EntityFrameworkCore and MSSQL Server as Database

Also added CORS to the API in Web API Part 2 - Adding CORS to ASP .NET Core Web API

and also completed the versioning in Web API Part 3 - Adding Versioning to the ASP .NET Core Web API

So We will continue from third part and start working on this.

Older ASP.NET Webforms and ASP.NET MVC applications, we have declared and initialized the key value pairs in web.config file appSettings section, same we have accessed with the help of 

System.Configuration.ConfigurationManager.AppSettings["SmtpPort"].ToString()

But in .NET Core appsettings section moved to appsettings.json and accessing value from the file is not a big deal.

Only difference between web.config appsetting and appsettings.json is xml for wen.config and json for appsettings.json, that's it.

Lets Start....

First, We will download the source code from Web API Part 3 - Adding Versioning to the ASP .NET Core Web API

1. Open project in Visual studio.

2. Go to appsettings.json and add the following keys

  "MailInfo": {
    "isMailRequired": true,
    "SMTPPort": 1000,
    "MailFrom": "test@mail.com"
  }

3. Go to Models folder and create the class MailInfo.cs and add below code

namespace My.Simple.Web.API.Models
{
    public class MailInfo
    {
        public bool IsMailRequired { get; set; }
        public string SMTPPort { get; set; }
        public string MailFrom { get; set; }
    }
}

4. Next go to Program class and add the dependency like below

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

Here is the screen


Above code will helps to load the appsettings.json detail to MailInfo class

In general word, it would automatically register the MailInfo and if the property name matches for inside this section we have IsMailRequired, SMTPPort, MailFrom that will be automatically injected.

5. Next go to LearningController and access the values with constructor injection

    public class LearningController : ControllerBase
    {
        private static AppDbContext _context;
        private readonly MailInfo _mailInfo;

        public LearningController(AppDbContext context, IOptions<MailInfo> mailInfo)
        {
            _context = context;
            _mailInfo = mailInfo.Value;
        }

IOptions:

IOptions is used to get the MailInfo Object.

IOptions Present in Microsoft.Extensions.Options namespace. It's a pretty small package which is not tied to ASP.NET Core, so it can be used independent of it.

IOptions service is used to bind strongly types options class to configuration section.

6. Create a action method SendMail

        [HttpGet("send-mail")]
        public IActionResult SendMail()
        {
            if (_mailInfo.IsMailRequired)
            {
                return Ok("mail sent to xyz@test.com from "+_mailInfo.MailFrom);
            }

            return Ok("Mail Failed");
        }

7. Then run the service and go to swagger, you could see the send-mail method exists


We are able to access the value from appsettings.json to controller. Its working fine without any issues.

Download Complete Source Code Here Download Source Code

Thats it for this article, I hope you enjoyed this article.

Let us know in case any concern through comment section.

See you in next article. Thanks much

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !