65.9K
CodeProject 正在变化。 阅读更多。
Home

在 Web.config 中自定义 SectionGroups 和 Sections

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.77/5 (21投票s)

2004 年 6 月 2 日

viewsIcon

129009

downloadIcon

645

为了在 web.config 的配置部分添加我们自己的 SectionGroups 和 Sections。

引言

本文介绍如何在应用程序中自定义 web.config 文件。

我们已经具备访问 web.config 中的 Appsettings 的功能。在某些情况下,我们需要根据应用程序的需求在 web.config 中声明我们自己的 SectionGroups 和 Sections。这将帮助开发人员从应用程序中的 sections 访问这些值。

这里,我在一个 SectionGroup 下创建了两个 Section

希望这篇文章能在您想要处理 web.config 中的 SectionGroups 时提供帮助。

代码

'write the following in the web.config
<configuration>
<configSections>
<!--Config section Group and Sections Declaration-->
<sectionGroup name="Company">
   <section name="AssociatedCompany" 
     type="System.Configuration.NameValueSectionHandler,System"/>
   <section name="Subsidiary" 
     type="System.Configuration.NameValueSectionHandler,System"/>
</sectionGroup>
</configSections>
.
.
.
.
.
.
<!--This For Section Declaration-->
<Company>
<AssociatedCompany>
<add key="A1" value="AWCompany"/>
<add key="A2" value="AXCompany"/>
<add key="A3" value="AYCompany"/>
<add key="A4" value="AZWCompany"/>
</AssociatedCompany>
<Subsidiary>
<add key="S1" value="AWCompany"/>
<add key="S2" value="AXCompany"/>
<add key="S3" value="AYCompany"/>
<add key="S4" value="AZWCompany"/>
</Subsidiary>
</Company>
</configuration>

现在,将以下内容写入代码隐藏文件 (VB)

Imports System.Collections.Specialized
'This Code will populate the Company Details into dropdownlist


 Dim config As New NameValueCollection
       
        'Getting Associated Company code from web.config

        config = ConfigurationSettings.GetConfig("Company/AssociatedCompany")
        If Not IsNothing(config) Then
            Dim inKeyCnt As Integer
            'Loop to populate all the company code in the dropdown list

            For inKeyCnt = 0 To config.Keys.Count - 1
               'DropDown List ID is ddlAssociation

      
                 ddlAssociation.Items.Add(config(inKeyCnt).ToString)
            Next

        End If
'Similary for Subsidiary also.

注意:如果在调用 GetCOnfig() 函数时遇到任何错误,请在 web.configSection 声明中提供公钥和版本。从您的框架中的 machine.config 文件中检查公钥和版本信息。例如

<section name="AssociatedCompany" 
  type="System.Configuration.NameValueSectionHandler, 
         System,Version=1.0.5000.0, Culture=neutral, 
         PublicKeyToken=b77a5c561934e089"/>
<section name="Subsidiary" 
  type="System.Configuration.NameValueSectionHandler,
         System,Version=1.0.5000.0, Culture=neutral, 
         PublicKeyToken=b77a5c561934e089"/>

如果您有任何建议,请与我联系。

再次感谢。

© . All rights reserved.