Original: http://gunnarpeipman.com/2014/11/asp-net-5-new-configuration-files-and-containers/
ASP. NET Vnext provides a new config file. A config file that can support multiple formats can be. json. ini. Xml. You can also write config handler to handle your custom format configuration files.
Configuration file
Suppose we have 3 config files
Config.json
{" ConnectionStrings": { "jsonconnectionstring": "JSON connection string"} }
Config.
<config> <ConnectionStrings> <xmlconnectionstring>xml Connection string</ Xmlconnectionstring> </ConnectionStrings></config>
Config.ini
[ConnectionStrings] iniconnectionstring = INI Connection string
The above 3 config are a structure although they are in different formats.
Depend on
Before we load the config file we need to add some dependencies to open Project.json add the penultimate and third lines (Microsoft.Framework.Configuration.XXX):
{ // ... " Dependencies ": { " Kestrel ":" 1.0.0-alpha4 ", " Entityframework.sqlserver ":" 7.0.0-ALPHA4 ", //... " Microsoft.AspNet.StaticFiles ":" 1.0.0-alpha4 ", " Microsoft.Framework.ConfigurationModel.Json ":" 1.0.0-ALPHA4 " , "Microsoft.Framework.ConfigurationModel.Xml": "1.0.0-alpha4", " Microsoft.VisualStudio.Web.BrowserLink.Loader ":" 14.0.0-alpha4 " } //...}
Loading configuration files
public class startup{public void Configure (Iapplicationbuilder app) { //Setup configuration sources var configuration = new configuration (); Configuration. Addjsonfile ("Config.json"); Configuration. Addinifile ("Config.ini"); Configuration. Addxmlfile ("config + +"); Configuration. Addenvironmentvariables (); ... }}
Now that the configuration file is loaded, let's use the powerful configuration object to read the config parameter.
Reading configuration parameters
If you like to read arguments of non-string type you can use the generic method get<t> ():
var size = Configuration. Get<int> ("Box:size");
Why do we need multiple configuration files
Why do we need a configuration system like this? The following scenarios are supported by this configuration system:
- We can use multiple configurationcontainers
- We can use the same configuration file in both Web and desktop programs.
Look at the code below.
Common Configurationvar configuration = new configuration (), configuration. Addjsonfile ("Config.json"); Addinifile ("Config.ini"); Addxmlfile ("config + +"); configuration. Addenvironmentvariables (); Mailer Configurationvar emailconfiguration = new Configuration (); Emailconfiguration.addinifile (" Advanced-mailer.ini "); SMS Configurationvar smsconfiguration = new Configuration (); Smsconfiguration.addxmlfile ("Sms.config");
ASP. 5:new Configuration files and containers