2013-02-19 46 views
0

我一直在尋找這個太長時間。我知道我只是在做一些愚蠢的事情,但我看不到它。在添加異常之前,我的集合始終爲空。添加之後,它總是被拋出。我錯過了什麼?自定義Web配置集合需要一組新的眼睛

我有一個web配置集合,看起來像這樣:

<section name="WorkOutGroups" type="System.Configuration.WorkOutGroupsSection"/> 

<WorkoutGroups> 
    <Workouts> 
     <add url="something.asp" /> 
     <add url="/subfolder/another.asp" /> 
     <add url="../default.asp" /> 
    </Workouts> 
</WorkoutGroups> 

我的課是這樣的:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Configuration; 
using System.Collections; 

namespace MySite.Configuration 
{ 
    public class WorkOutsGroupsSection : ConfigurationSection 
    { 
     [ConfigurationProperty("WorkOut", IsDefaultCollection = false)] 
     [ConfigurationCollection(typeof(WorkOutCollection))] 
     public WorkOutCollection WorkOut 
     { 
      get 
      { 
       var WorkOut = (WorkOutCollection)base["WorkOut"]; 
       return WorkOut; 
      } 
     } 
    } 

    public class WorkOutCollection : ConfigurationElementCollection 
    { 
     protected override ConfigurationElement CreateNewElement() 
     { 
      return new WorkOutElement(); 
     } 

     protected override object GetElementKey(ConfigurationElement element) 
     { 
      object result = null; 
      if (element is WorkOutElement) 
      { 
       result = ((WorkOutElement)element).WorkOut; 
      } 
      return result; 
     } 

     public WorkOutElement this[int index] 
     { 
      get { return (WorkOutElement)BaseGet(index); } 
     } 
    } 

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

    public static class WorkOutsGroups 
    { 
     static WorkOutsGroupsSection WorkOutsGroupsSection 
     { 
      get 
      { 
       var section = ConfigurationManager.GetSection("WorkOutsGroups") 
        as WorkOutsGroupsSection; 
       if (section != null) 
       { 
        return section; 
       } 
       throw new ConfigurationErrorsException("WorkOutsGroups Configuration not found"); 
      } 
     } 

     public static IEnumerable<string> GetWorkOut() 
     { 
      var results = WorkOutsGroupsSection.WorkOut 
        .OfType<WorkOutElement>() 
        .Select(p => p.WorkOut); 

      return results.ToArray(); 
     } 
    } 
} 

和我採取這樣的:

foreach (var url in Workout.GetWorkout()) 
{ 
    if (link.Value.Contains(url.ToString())) 
     returnValue = true; 
} 

回答

0

拼寫檢查:

ConfigurationManager.GetSection("WorkOutsGroups") 

的節名是WorkOutGroupsWorkOutsGroups

0

你在你的C#代碼有

var WorkOut = (WorkOutCollection)base["WorkOut"]; 

,但鍛鍊小號在你的配置。

也許這就是原因。