2017-02-01 2 views
0

私は、Xmlで比較的複雑なオブジェクトを定義する<configSection>を作成することによって、AppのApp.configを拡張することを任されました。App.configの何が問題なのですか?

<configuration> 
    <appSettings> 
    <add key="MinWaitTime" value="150" /> 
    <add key="MaxWaitTime" value="900" /> 
    </appSettings> 
    <configSections> 
    <section name="clientconfig" type="KeepWarm.ClientConfig" /> 
    </configSections> 
    <clientconfig username="test user" password="test password"> 
    <urls> 
     <add url="test1" /> 
     <add url="test2" /> 
     <add url="test3" /> 
    </urls> 
    </clientconfig> 
</configuration> 

結局、私は複数の<clientconfig>を定義できるようにする必要がありますが、私はすでに苦しんで一つだけが動作するように取得しています。configは次のようになります。

しかし
namespace KeepWarm 
{ 
    public class ClientConfig : ConfigurationSection 
    { 
     [ConfigurationProperty("username", IsRequired = true)] 
     public string UserName 
     { 
      get { return (string)base["username"]; } 
      set { base["username"] = value; } 
     } 

     [ConfigurationProperty("password", IsRequired = true)] 
     public string Password 
     { 
      get { return (string)base["password"]; } 
      set { base["password"] = value; } 
     } 

     [ConfigurationProperty("urls", IsRequired = true)] 
     public UrlCollection Urls 
     { 
      get { return (UrlCollection)base["urls"]; } 
      set { base["urls"] = value; } 
     } 
    } 

    [ConfigurationCollection(typeof(UrlElement))] 
    public class UrlCollection : ConfigurationElementCollection 
    { 
     protected override ConfigurationElement CreateNewElement() 
     { 
      return new UrlElement(); 
     } 

     protected override object GetElementKey(ConfigurationElement element) 
     { 
      return ((UrlElement)element).Url; 
     } 
    } 

    public class UrlElement : ConfigurationElement 
    { 
     [ConfigurationProperty("url", IsKey = true, IsRequired = true)] 
     public string Url 
     { 
      get { return (string)this["url"]; } 
      set { base["url"] = value; } 
     } 
    } 
} 

私は私の設定にアクセスしようとするたびに、次のように:

var minWaitTime = int.Parse(ConfigurationManager.AppSettings["MinWaitTime"]); 

私はSystem.Configuration.ConfigurationErrorsExceptionを取得します。

私はさまざまな例をオンラインで見てきましたが、私の場合は何も役立たないようです。私は間違って何をしていますか?

+3

通常、例外に含まれるすべての情報を提供するようお願いします。しかし、私は 'configSections'が' appSettings'の前にapp.configに現れる必要があると思います。 –

答えて

1

あなたの問題は、あなたの設定セクションが宣言されている場所です。 configSectionsタグは、構成ノードの直後にある必要があります。試してみてください:

<configuration> 
    <configSections> 
    <section name="clientconfig" type="KeepWarm.ClientConfig" /> 
    </configSections> 
    <appSettings> 
    <add key="MinWaitTime" value="150" /> 
    <add key="MaxWaitTime" value="900" /> 
    </appSettings> 
    <clientconfig username="test user" password="test password"> 
    <urls> 
     <add url="test1" /> 
     <add url="test2" /> 
     <add url="test3" /> 
    </urls> 
    </clientconfig> 
</configuration> 
関連する問題