It had a few twists and turns. I modified this answer to keep up to date with ASP.NET Core 2.0 (as of 02/26/2018).
This is mainly taken from official documentation :
To work with the settings in your ASP.NET application, it is recommended that you only create an instance of Configuration in your Startup class applications. Then use the Options template to access individual settings. Say we have an appsettings.json file that looks like this:
{ "MyConfig": { "ApplicationName": "MyApp", "Version": "1.0.0" } }
And we have a POCO object representing the configuration:
public class MyConfig { public string ApplicationName { get; set; } public int Version { get; set; } }
Now we create the configuration in Startup.cs :
public class Startup { public IConfigurationRoot Configuration { get; set; } public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); Configuration = builder.Build(); } }
Note that appsettings.json will be registered by default in .NET Core 2.0. We can also register appsettings.{Environment}.json for each environment, if necessary.
If we want to enter our configuration into our controllers, we will need to register it at runtime. We do this through Startup.ConfigureServices :
public void ConfigureServices(IServiceCollection services) { services.AddMvc();
And we introduce it like this:
public class HomeController : Controller { private readonly IOptions<MyConfig> config; public HomeController(IOptions<MyConfig> config) { this.config = config; }
Full Startup class:
public class Startup { public IConfigurationRoot Configuration { get; set; } public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); Configuration = builder.Build(); } public void ConfigureServices(IServiceCollection services) { services.AddMvc();
Yuval Itzchakov Jul 16 '15 at 12:05 2015-07-16 12:05
source share