1、web.config 配置文件设置
<configSections> <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --> <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture= neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> <!-- type="类型,命名空间" --> <section name="securevalid" type="JXAPI.JXSdk.Config.SecureConfigSection,JXAPI.JXSdk" /> </configSections>
<securevalid ipvalid="0"> <secures> <add source="other" pwd="123456" url="http://xxxx/" ip="192.168.0.1,127.0.0.1"></add> <add source="employee" pwd="" url="http://xxxx.com/employee/get" ip=""></add> </secures> </securevalid>
2、SecureConfigSection 类
namespace JXAPI.JXSdk.Config { public class SecureConfigSection : ConfigurationSection { private static SecureConfigSection _Instance = null; public static SecureConfigSection Instance { get { if (_Instance == null) { _Instance = ConfigurationManager.GetSection("securevalid") as SecureConfigSection; } return _Instance; } } [ConfigurationProperty("ipvalid", IsRequired = true)] public string IPValid { get { return this["ipvalid"].ToString(); } } [ConfigurationProperty("secures", IsDefaultCollection = true)] public SecureCollection Secures { get { return this["secures"] as SecureCollection; } } } public class SecureCollection : ConfigurationElementCollection { protected override ConfigurationElement CreateNewElement() { return new SecureElement(); } protected override object GetElementKey(ConfigurationElement element) { return ((SecureElement)element).Source; } public SecureElement this[int index] { get { return this.BaseGet(index) as SecureElement; } } new public SecureElement this[string Name] { get { return (SecureElement)BaseGet(Name); } } new public int Count { get { return base.Count; } } } public class SecureElement : ConfigurationElement { [ConfigurationProperty("source", IsRequired = true)] public string Source { get { return this["source"].ToString(); } } [ConfigurationProperty("pwd", IsRequired = true)] public string APPPWD { get { return this["pwd"].ToString(); } } [ConfigurationProperty("url", IsRequired = true)] public string URL { get { return this["url"].ToString(); } } [ConfigurationProperty("ip", IsRequired = true)] public string IP { get { return this["ip"].ToString(); } } } }
3、应用
var url = JXAPI.JXSdk.Config.SecureConfigSection.Instance.Secures["employee"].URL; var ip = JXAPI.JXSdk.Config.SecureConfigSection.Instance.Secures["other"].IP; var ipValid = JXAPI.JXSdk.Config.SecureConfigSection.Instance.IPValid