更新:自定义配置太难了!>.< 虽然我学到了一些关于 XML 的东西;显然不可能将 CDATA 存储在元素中,所以我重新表述了这个问题以适应修改后的结构。为了清楚起见,请问我任何问题。我一直在研究这个问题大约一个月的时间,并且不断遇到各种问题。
我一直在关注下面引用的文章中的 MSDN 示例,但我无法将这个概念应用到我的案例中。我的项目是 VS2010 中的 VB.NET 4.0 Web 应用程序,但 C# 中的答案也可以(只要解决方案在 VB 中有效)。:) 这是相关代码:
致电:
Dim conf As ApiSection = CType(ConfigurationManager.GetSection("remoteServiceApi/site"), ApiSection)
异常(ConfigurationErrorsException)
The element <site> may only appear once in this section.
请注意以下相关代码...
架构:
<xs:element name="ApiSection">
<xs:complexType>
<xs:sequence>
<xs:element name="site" id="environment" nillable="false" maxOccurs="unbounded">
<xs:complexType>
<xs:attribute name="environment" use="required">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value="Production"></xs:enumeration>
<xs:enumeration value="Sandbox"></xs:enumeration>
</xs:restriction>
</xs:simpleType>
</xs:attribute>
<xs:attribute name="APIKey" type="xs:string" use="required" />
<xs:attribute name="APIUsername" type="xs:string" use="required" />
<xs:attribute name="APIPassword" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
即使我在 web.config 文件的架构集中添加并激活了上述内容,它似乎并没有真正起作用。:(这可能是问题吗?
网络配置:
<configSections>
<sectionGroup name="remoteServiceApi">
<section name="site" type="RemoteServiceApi.ApiSection" />
</sectionGroup>
</configSections>
<remoteServiceApi environment="Sandbox">
<site environment="Sandbox"
APIKey="reallyLongHashKeyDev"
APIUsername="samplejoe"
APIPassword="joespass" />
<site environment="Production"
APIKey="reallyLongHashKeyProd"
APIUsername="samplejoe"
APIPassword="joespass" />
</remoteServiceApi>
类文件:
Imports System.Configuration
Namespace RemoteServiceApi
Public Class ApiSection
Inherits ConfigurationSection
<ConfigurationProperty("site", IsRequired:=True)> _
Public Property site() As SiteElement
Get
Return CType(Me("site"), SiteElement)
End Get
Set(value As SiteElement)
Me("site") = value
End Set
End Property
End Class
Public Class SiteElement
Inherits ConfigurationElement
<ConfigurationProperty("Environment", DefaultValue:="Sandbox", IsRequired:=True)> _
Public Property Environment() As String
Get
Return CStr(Me("Environment"))
End Get
Set(value As String)
Me("Environment") = value
End Set
End Property
<ConfigurationProperty("APIKey", IsRequired:=True)> _
Public ReadOnly Property APIKey() As String
Get
Return CStr(Me("APIKey"))
End Get
End Property
<ConfigurationProperty("APIUsername", IsRequired:=True)> _
Public ReadOnly Property APIUsername() As String
Get
Return CStr(Me("APIUsername"))
End Get
End Property
<ConfigurationProperty("APIPassword", IsRequired:=True)> _
Public ReadOnly Property APIPassword() As String
Get
Return CStr(Me("APIPassword"))
End Get
End Property
End Class
Public Enum Environment
Production
Sandbox
End Enum
End Namespace
我用作指南的参考资料:
- 如何:使用 ConfigurationSection 创建自定义配置部分
- 创建自定义配置(发布于 2004 年,请谨慎关注)