關於配置文件的目錄:[Asp.net 5] Configuration-新一代的配置文件
在前面我們介紹了,系統中用IConfigurationSource表示不同配置文件的來源,起到讀取、設置、加載配置文件的作用。而虛擬類ConfigurationSource繼承接口IConfigurationSource,其他類又由ConfigurationSource派生(當然我們也可以寫繼承自接口IConfigurationSource類,但是沒什麼必要)。下面是實現不同配置方式的工程:
下面我們主要以測試用例的方式講解Json與XMl配置文件的源碼以及實用方式:
Microsoft.Framework.Configuration.Json
Json的配置文件:在實現的過程中使用Newtonsoft.Json的NuGet程序包,這是非常有名的json操作組件,如果單獨涉及到.net的Json操作,推薦使用該組件。
public void PropertiesAreSortedByNumberOnlyFirst() { var json = @"{ 'setting': { 'hello': 'a', 'bob': 'b', '42': 'c', '4':'d', '10': 'e', '1text': 'f', } }"; var jsonConfigSource = new JsonConfigurationSource(TestStreamHelpers.ArbitraryFilePath); jsonConfigSource.Load(TestStreamHelpers.StringToStream(json)); var builder = new ConfigurationBuilder(); builder.Add(jsonConfigSource, load: false); var config = builder.Build(); var configurationSection = config.GetConfigurationSection("setting"); var indexConfigurationSections = configurationSection.GetConfigurationSections().ToArray(); Assert.Equal(6, indexConfigurationSections.Count()); Assert.Equal("4", indexConfigurationSections[0].Key); Assert.Equal("10", indexConfigurationSections[1].Key); Assert.Equal("42", indexConfigurationSections[2].Key); Assert.Equal("1text", indexConfigurationSections[3].Key); Assert.Equal("bob", indexConfigurationSections[4].Key); Assert.Equal("hello", indexConfigurationSections[5].Key); } PropertiesAreSortedByNumberOnlyFirst
Microsoft.Framework.Configuration.Xml
xml配置文件,在日常中用的也是比較多的,傳統的配置文件就是xml的。[該處實現是支持內容加密的,具體不了解,略]
下面是xml文件的常規用法:
public void SupportAndIgnoreXMLDeclaration() { var xml = @"<?xml version='1.0' encoding='UTF-8'?> <settings> <Data> <DefaultConnection> <ConnectionString>TestConnectionString</ConnectionString> <Provider>SqlClient</Provider> </DefaultConnection> <Inventory> <ConnectionString>AnotherTestConnectionString</ConnectionString> <Provider>MySql</Provider> </Inventory> </Data> </settings>"; var xmlConfigSrc = new XmlConfigurationSource(ArbitraryFilePath); xmlConfigSrc.Load(TestStreamHelpers.StringToStream(xml)); Assert.Equal("TestConnectionString", xmlConfigSrc.Get("Data:DefaultConnection:ConnectionString")); Assert.Equal("SqlClient", xmlConfigSrc.Get("Data:DefaultConnection:Provider")); Assert.Equal("AnotherTestConnectionString", xmlConfigSrc.Get("Data:Inventory:ConnectionString")); Assert.Equal("MySql", xmlConfigSrc.Get("Data:Inventory:Provider")); } XMLConfigurationSource