我正在尝试从.NET 4.0应用程序中的自定义配置部分读取值。但是,在检查值时,它们始终显示默认值,而不是我期望的自定义值。
这是我的班级:
using System;
using System.Configuration;
namespace TestNamespace
{
public class TestSection : ConfigurationSection
{
[ConfigurationProperty("applicationAccessID", IsRequired = true)]
public string ApplicationAccessID { get; set; }
[ConfigurationProperty("username", IsRequired = true)]
public Guid Username { get; set; }
[ConfigurationProperty("password", IsRequired = true)]
public Guid Password { get; set; }
}
}
我已将以下项目添加到配置文件中:
<configuration>
<configSections>
<sectionGroup name="myCustomConfiguration">
<section name="testSection" type="TestNamespace.TestSection,MyAssembly"/>
</sectionGroup>
</configSections>
<myCustomConfiguration>
<myAuthenticationSection applicationAccessID="1" username="9A36EC78-76B0-477B-9E36-613C13AE86BB" password="589A8696-2B9B-4ADD-906E-7245D387B594" />
</myCustomConfiguration>
...
此行返回TestSection的实例,但它不是从配置中读取自定义值:
ConfigurationManager.GetSection("myCustomConfiguration/myAuthenticationSection")
有什么建议吗?
编辑: 删除组后,这是我更新的配置文件:
<configuration>
<configSections>
<section name="testSection" type="TestNamespace.TestSection,MyAssembly"/>
</configSections>
<myAuthenticationSection applicationAccessID="1" username="9A36EC78-76B0-477B-9E36-613C13AE86BB" password="589A8696-2B9B-4ADD-906E-7245D387B594" />
...
同样的问题......
答案 0 :(得分:2)
您正在使用群组,因此您还需要实施群组处理程序:
public class MySettingsConfigurationGroup : ConfigurationSectionGroup
{
}
还有更多内容,请点击此处:http://www.codeproject.com/KB/dotnet/mysteriesofconfiguration.aspx
更新
public class TestSection : ConfigurationSection
{
private static TestSection _testSection
= ConfigurationManager.GetSection("TestSection") as TestSection;
public static TestSection Settings
{
get
{
return _testSection;
}
}
[ConfigurationProperty("applicationAccessID", IsRequired = true)]
public string ApplicationAccessID { get; set; }
[ConfigurationProperty("username", IsRequired = true)]
public Guid Username { get; set; }
[ConfigurationProperty("password", IsRequired = true)]
public Guid Password { get; set; }
}
string id = TestSection.Settings.applicationAccessID;
此外,名称需要匹配:
<testSection applicationAccessID="1" username="9A36EC78-76B0-477B-9E36-613C13AE86BB" password="589A8696-2B9B-4ADD-906E-7245D387B594" />
答案 1 :(得分:2)
我不知道这个问题是否仍然有效,但无论如何。
在处理ConfigurationElement
时,您需要解决配置元素是值集合的问题,因此您不读取值。
我会替换这样的东西:
[ConfigurationProperty("applicationAccessID", IsRequired = true)]
public string ApplicationAccessID
{
get { return (string)this["applicationAccessID"]; }
set { this["applicationAccessID"] = value; }
}
[ConfigurationProperty("username", IsRequired = true)]
public Guid Username
{
get { return (Guid)this["username"]; }
set { this["username"] = value; }
}
[ConfigurationProperty("password", IsRequired = true)]
public Guid Password
{
get { return (Guid)this["password"]; }
set { this["password"] = value; }
}