如何从web.config读取自定义部分?

时间:2018-01-22 06:29:30

标签: c# iis

我正在实现一些IIS模块来处理应用程序的web.config。 我已经有了模块的工作部分,但我设法从web.config读取自定义部分。

我将自定义部分的以下IIS架构添加到标准文件夹%windir%\ system32 \ inetsrv \ config \ schema \:

<configSchema>
  <sectionSchema name="myCustomSection">
    <element name="customCollection">
        <collection addElement="customItem">            
            <attribute name="name" type="string" />
            <attribute name="path" type="string" />
        </collection>
    </element>
  </sectionSchema>
</configSchema>

以下XML适用于sectionSchema:

<configuration>
    <myCustomSection>
      <customCollection>
        <customItem name="item1" path="D:\item1\web.config" />
        <customItem name="item2" path="D:\item2\web.config" />
        <customItem name="item3" path="D:\item3\web.config" />                   
      </customCollection>
    </myCustomSection>
...
</configuration>

我的代码可以读取myCustomSection和element customCollection部分,但customCollection为空=(

代码阅读:

    [ModuleServiceMethod(PassThrough = true)]
    public PropertyBag GetAppSettings(string applicationPath)
    {
        var bag = new PropertyBag();
        var manager = this.ManagementUnit.ServerManager;
        var configurationPath = ManagementConfigurationPath.CreateApplicationConfigurationPath(ManagementUnit.ConfigurationPath.SiteName, applicationPath);
        var effectiveConfigurationPath = configurationPath.GetEffectiveConfigurationPath(ManagementScope.Server);
        var configuration = manager.GetWebConfiguration(ManagementUnit.ConfigurationMap, effectiveConfigurationPath);

        var claimsSection = configuration.GetSection("myCustomSection");
        var child = claimsSection.GetChildElement("customCollection");
        var childCollection = child.GetCollection(); //count = 0
        // var childCollection = child.GetCollection("customItem"); throw exception

        ...
        return bag;
    }

可能有人知道如何从收集中收集孩子吗?

更新

不幸的是,我将错误的applicationPath传递给了这个函数。 此外,有更简洁的代码来做同样的事情:

var section = ManagementUnit.Configuration.GetSection("myCustomSection");
var child = sect.GetChildElement("customCollection");
var childCollection = child.GetCollection();

1 个答案:

答案 0 :(得分:0)

获取原始XML From部分并处理该XML以获取属性值。

       var claimsSection = config.GetSection("myCustomSection");
        string xml = claimsSection.SectionInformation.GetRawXml();
        System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument();
        xDoc.LoadXml(xml);

        System.Xml.XmlNode xList = xDoc.ChildNodes[0];
        for (int i =0; i< xList.ChildNodes.Count; i++)
        {
            foreach (System.Xml.XmlNode xNodo in xList.ChildNodes[i])
            {
                Console.WriteLine((xNodo.Attributes[0].Value));

            }
        }