首页 / C# / c# – 自定义配置部分.NET
c# – 自定义配置部分.NET
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 自定义配置部分.NET,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2346字,纯文字阅读大概需要4分钟。
内容图文
![c# – 自定义配置部分.NET](/upload/InfoBanner/zyjiaocheng/786/5910ad58d33e42849ef7630015c7461b.jpg)
我正在尝试按照教程:http://devlicio.us/blogs/derik_whittaker/archive/2006/11/13/app-config-and-custom-configuration-sections.aspx创建一个自定义配置部分来保存一些API凭据.我已将以下内容添加到我的Web.config文件中:
<!-- Under configSections -->
<section name="providers" type="EmailApiAccess.Services.ProviderSection, EmailApiAccess.Services"/>
<!-- Root Level -->
<providers>
<add name="ProviderName" username="" password ="" host="" />
</providers>
并创建了以下类:
public class ProviderSection: ConfigurationSection
{
[ConfigurationProperty("providers")]
public ProviderCollection Providers
{
get { return ((ProviderCollection)(base["providers"])); }
}
}
[ConfigurationCollection(typeof(ProviderElement))]
public class ProviderCollection : ConfigurationElementCollection
{
public ProviderElement this[int index]
{
get { return (ProviderElement) BaseGet(index); }
set
{
if (BaseGet(index) != null)
BaseRemoveAt(index);
BaseAdd(index, value);
}
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((ProviderElement)(element)).name;
}
protected override ConfigurationElement CreateNewElement()
{
return new ProviderElement();
}
}
public class ProviderElement: ConfigurationElement
{
public ProviderElement() { }
[ConfigurationProperty("name", DefaultValue="", IsKey=true, IsRequired=true)]
public string name
{
get { return (string)this["name"]; }
set { this["name"] = value; }
}
[ConfigurationProperty("username", DefaultValue = "", IsRequired = true)]
public string username
{
get { return (string)this["username"]; }
set { this["username"] = value; }
}
[ConfigurationProperty("password", DefaultValue = "", IsRequired = true)]
public string password
{
get { return (string)this["password"]; }
set { this["password"] = value; }
}
[ConfigurationProperty("host", DefaultValue = "", IsRequired = false)]
public string host
{
get { return (string)this["host"]; }
set { this["host"] = value; }
}
}
但是,当我尝试使用以下代码实现代码时:
var section = ConfigurationManager.GetSection("providers");
ProviderElement element = section.Providers["ProviderName"];
var creds = new NetworkCredential(element.username, element.password);
我得到一个错误,说“对象”不包含“提供者”的定义….
任何帮助,将不胜感激.
解决方法:
ConfigurationManager.GetSection返回类型为object的值,而不是您的自定义配置节.请尝试以下方法:
var section = ConfigurationManager.GetSection("providers") as ProviderSection;
内容总结
以上是互联网集市为您收集整理的c# – 自定义配置部分.NET全部内容,希望文章能够帮你解决c# – 自定义配置部分.NET所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。