1
我在web.config中使用<configSections></configSections>.
Web.config文件 - 自定義配置,以保持集合的集合
的,我想標籤的結構設置自定義裏面的配置和在web.config中創建的是:
<TwitterCredentialsSectionGroup>
<TwitterCredentialsSection>
<accounts>
<account id="ID1">
<add key="ConsumerKey" value="..."/>
<add key="ConsumerSecretKey" value="..."/>
<add key="AccessToken" value="..."/>
<add key="AccesstSecretToken" value="..."/>
</account>
</accounts>
</TwitterCredentialsSection>
</TwitterCredentialsSectionGroup>
我註冊configSections標籤內我的自定義配置部分使用以下標籤:
<configSections>
<sectionGroup name="TwitterCredentialsSectionGroup">
<section name="TwitterCredentialsSection" type="TwitterIntegration.TwitterCredentialsSection"
allowLocation="true" allowDefinition="Everywhere" />
</sectionGroup>
這裏有2個不同的收集要素,即:
- 賬戶(持有每個Twitter賬戶鍵)
- 賬戶(其將持有的所有Twitter帳戶實例/標籤)
現在我的代碼文件自定義配置是這樣的:
namespace TwitterIntegration
{
public class TwitterCredentialsSection : ConfigurationSection
{
[ConfigurationProperty("accounts")]
public AccountCollection Accounts
{
get
{
return (AccountCollection)this["accounts"];
}
}
[ConfigurationProperty("account")]
public AccountElement Account
{
get
{
return (AccountElement)this["account"];
}
}
}
public class TwitterKeyElement : ConfigurationElement
{
[ConfigurationProperty("key",IsKey=true, IsRequired=true)]
public String Key
{
get
{
return (String)this["key"];
}
}
[ConfigurationProperty("value")]
public String Value
{
get
{
return (String)this["value"];
}
}
}
[ConfigurationCollection(typeof(TwitterKeyElement))]
public class AccountElement : ConfigurationElementCollection
{
[ConfigurationProperty("id", IsRequired = true, IsKey = true)]
public string ID
{
get
{
return (string)this["id"];
}
}
protected override ConfigurationElement CreateNewElement()
{
return new TwitterKeyElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((TwitterKeyElement)element).Key;
}
}
[ConfigurationCollection(typeof(AccountElement))]
public class AccountCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new AccountElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((AccountElement)element).ID;
}
}
}
現在,當我嘗試讀取web.config中,使用下面的代碼,我得到一個錯誤:
TwitterCredentialsSection objtcsection = (ConfigurationManager.GetSection("TwitterCredentialsSectionGroup/TwitterCredentialsSection") as TwitterCredentialsSection);
錯誤: **分析器錯誤信息:無法識別的元素「帳戶」。
Source Error:
Line 19: <TwitterCredentialsSection>
Line 20: <accounts>
Line 21: <account id="ID1">
Line 22: <add key="ConsumerKey" value="W0SKMPuXzml2CHGsMSoHZA"/>
Line 23: <add key="ConsumerSecretKey" value="kaAS0CgeQqcTWjTvYsie8Owtl8o6N8hcOclY9bKlu4"/>
**
任何人都可以請建議我的代碼有什麼問題嗎?
感謝