We will learn the following ways to use Configuration in ASP.NET Core project.
Here is the default way to read the contents in appsettings.json
.
public IConfigurationRoot Configuration { get; }
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
var siteName = Configuration["Config:SiteName"];
}
{
"Config": {
"SiteName": "ASP.NET Core X Angular2",
"SiteOwner": "2016 JB"
}
}
Create a class to store the configuration values.
public class ConfigManager
{
public string SiteName { get; set; }
public string SiteOwner { get; set; }
}
Then inject the configurations as a ConfigManager
object to the Service container.
public void ConfigureServices(IServiceCollection services)
{
//Skip…
services.Configure<ConfigManager>(Configuration.GetSection("Config"));
}
private ConfigManager _configManager = null;
public HomeController(IOptions<ConfigManager> options)
{
IOptions<ConfigManager> cfgMangerOptions = options;
this._configManager = cfgMangerOptions.Value;
}
public IActionResult Index()
{
ViewBag.Title = this._configManager.SiteName;
ViewBag.Owner = this._configManager.SiteOwner;
return View();
}
Result:
Here is the other simple way to make the configurations available at any class, not just Controller. Just create a static class to store them.
public static class ConfigProvider
{
public static string SiteName { get; set; }
public static string SiteOwner { get; set; }
}
public void ConfigureServices(IServiceCollection services)
{
//Skip …
var configManager = new ConfigManager();
Configuration.GetSection("Config").Bind(configManager);
ConfigProvider.SiteName = configManager.SiteName;
ConfigProvider.SiteOwner = configManager.SiteOwner;
}
Notice that we could bind the configuration values recursively into a complex class with Configuration.GetSection("Config").Bind()
function.
ViewBag.Title = ConfigProvider.SiteName;
ViewBag.Owner = ConfigProvider.SiteOwner;
Result :
Requires ASP.NET Core 1.1 or higher.
ASP.NET Core 1.1 and higher versions support reloading configuration data when the configuration file has changed. Take a look at the sample in ASP.NET Core documents.