From Asp.net core 2.2 to above you can code as below:
Step 1. Create an AppSettings class file.
This file contains some methods to help get value by key from the appsettings.json file. Look like as code below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ReadConfig.Bsl
{
public class AppSettings
{
private static AppSettings _instance;
private static readonly object ObjLocked = new object();
private IConfiguration _configuration;
protected AppSettings()
{
}
public void SetConfiguration(IConfiguration configuration)
{
_configuration = configuration;
}
public static AppSettings Instance
{
get
{
if (null == _instance)
{
lock (ObjLocked)
{
if (null == _instance)
_instance = new AppSettings();
}
}
return _instance;
}
}
public string GetConnection(string key, string defaultValue = "")
{
try
{
return _configuration.GetConnectionString(key);
}
catch
{
return defaultValue;
}
}
public T Get<T>(string key = null)
{
if (string.IsNullOrWhiteSpace(key))
return _configuration.Get<T>();
else
return _configuration.GetSection(key).Get<T>();
}
public T Get<T>(string key, T defaultValue)
{
if (_configuration.GetSection(key) == null)
return defaultValue;
if (string.IsNullOrWhiteSpace(key))
return _configuration.Get<T>();
else
return _configuration.GetSection(key).Get<T>();
}
public static T GetObject<T>(string key = null)
{
if (string.IsNullOrWhiteSpace(key))
return Instance._configuration.Get<T>();
else
{
var section = Instance._configuration.GetSection(key);
return section.Get<T>();
}
}
public static T GetObject<T>(string key, T defaultValue)
{
if (Instance._configuration.GetSection(key) == null)
return defaultValue;
if (string.IsNullOrWhiteSpace(key))
return Instance._configuration.Get<T>();
else
return Instance._configuration.GetSection(key).Get<T>();
}
}
}
Step 2. Initial configuration for AppSettings object
We need to declare and load appsettings.json file when the application starts, and load configuration information for AppSettings object. We will do this work in the constructor of the Startup.cs file.
Please notice line AppSettings.Instance.SetConfiguration(Configuration);
public Startup(IHostingEnvironment evm)
{
var builder = new ConfigurationBuilder()
.SetBasePath(evm.ContentRootPath)
.AddJsonFile("appsettings.json", true, true)
.AddJsonFile($"appsettings.{evm.EnvironmentName}.json", true)
.AddEnvironmentVariables();
Configuration = builder.Build(); // load all file config to Configuration property
AppSettings.Instance.SetConfiguration(Configuration);
}
Okay, now I have an appsettings.json file with some keys as below:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"ConnectionString": "Data Source=localhost;Initial Catalog=ReadConfig;Persist Security Info=True;User ID=sa;Password=12345;"
},
"MailConfig": {
"Servers": {
"MailGun": {
"Pass": "65-1B-C9-B9-27-00",
"Port": "587",
"Host": "smtp.gmail.com"
}
},
"Sender": {
"Email": "[email protected]",
"Pass": "123456"
}
}
}
Step 3. Read config value from an action
I make demo an action in Home controller as below :
public class HomeController : Controller
{
public IActionResult Index()
{
var connectionString = AppSettings.Instance.GetConnection("ConnectionString");
var emailSender = AppSettings.Instance.Get<string>("MailConfig:Sender:Email");
var emailHost = AppSettings.Instance.Get<string>("MailConfig:Servers:MailGun:Host");
string returnText = " 1. Connection String \n";
returnText += " " +connectionString;
returnText += "\n 2. Email info";
returnText += "\n Sender : " + emailSender;
returnText += "\n Host : " + emailHost;
return Content(returnText);
}
}
And below is the result:
For more information, you can refer article get value from appsettings.json in asp.net core for more detail code.