The configuration system in ASP.NET 5 has been completely overhauled and the entire web.config/app.config method has been replaced by a new pluggable system. The default implementation uses a config.json file (see below) as storage however other providers can be used.
// config.json
{
"AppSettings": {
"SiteTitle": "My Website's Title"
}
}
Properties for configuration values can also be accessed via a related class that match values in the configuration file i.e.
namespace MyProject
{
public class AppSettings
{
public string SiteTitle { get; set; }
}
}
Hooking up Configuration
The basic setup is configured during the startup of the application within the Startup
method of the Startup.cs
class. Noteby default there are two configuration files added config.json
and config.[Environment].json
.
Once the application is bootstrapped, the ConfigurationServices
method is fired where you can map configuration values to the specific configuration class. This code basically maps the AppSettings
configuration key to an instance of a configuration class i.e. ‘AppSettings.cs`.
public IConfiguration Configuration { get; set; }
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
{
var builder = new ConfigurationBuilder(appEnv.ApplicationBasePath)
.AddJsonFile("config.json")
.AddJsonFile($"config.{env.EnvironmentName}.json", optional: true);
Configuration = builder.Build();
}
public void ConfigureServices(IServiceCollection services)
{
services.Configure<AppSettings>(Configuration.GetConfigurationSection("AppSettings"));
}
Using Configuration Values
Accessing the configuration values can be done by injecting the AppSettings
class into your controller or view. The below example injects the class into your controller.
namespace MyProject.Controllers
{
public class HomeController : Controller
{
private readonly IOptions<AppSettings> _appSettings;
public HomeController(IOptions<AppSettings> appSettings)
{
_appSettings = appSettings;
}
}
}
The AppSettings
can also be injected directly into your view using a new @inject
tag.
@inject Microsoft.Framework.OptionsModel.IOptions<AppSettings> AppSettings
<h1>@AppSettings.Options.SiteTitle</h1>