Access SMTP Detail from appsettings.json in Class Library Using C#.Net

How to get the email server smtp detail defined in appsettings.json in asp.net core 8 mvc application using c#.net in a class library by passing key.
In today's article I will show you a simple tutorial with example how you can access the SMTP configuration detail from the appsettings.json file in asp.net core mvc using c#.net in a class library. Here is an example of smtp detail.

SMTP detail

 Now create a asp.net core 8 mvc application in solution and add a class library. Now in class library add a class file and add the below code.
namespace Project
{
    public static class TestClassFile
    {
        public static string GetValue(string key)
        {
            var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json", optional: false);
            IConfiguration config = builder.Build();
            string value = config.GetValue<string>(key);
            return value;
        }
    }
} 
Here I have created a method and in this method I have passed a parameter named as key, this will be a method which we can use to return the value of passed key. This methos we will pass the key value from controller. Refer the below code.
[HttpGet]
public IActionResult Index()
{
    string hostname = TestClassFile.GetValue("Smtp:Host");
    string port = TestClassFile.GetValue("Smtp:Port");
    string loginid = TestClassFile.GetValue("Smtp:LoginId");
    string password = TestClassFile.GetValue("Smtp:password");
    string enablessl = TestClassFile.GetValue("Smtp:EnableSsl");
    return View();
} 
Here I have access the methos defined in class library and passed the key value from to get the SMTP detail. Now let's run the code to check the output.

Value of passed key
Now let's check the controller. 

Controller Value

Post a Comment