ASP.NET下使用xml反序列化、缓存依赖实现个性化配置文件的实时生效
因为一些配置属性比较多,存在多组属性,因此结合xml解析、缓存技术,实现配置文化的自动解析、存入缓存、缓存依赖实时更新配置内容。
配置文件反序列化存入缓存的核心方法:
publicClass.SettingsGetSettings()
{
if(HttpRuntime.Cache["settings"]!=null)
return(Class.Settings)HttpRuntime.Cache["settings"];
stringrootPath=GetPath();
#regionrootPath
if(rootPath=="")
{
log.Write(MsgType.Fatal,"配置文件根目录rootPath为空");
returnnull;
}
else
{
if(!rootPath.EndsWith("\\"))
rootPath+="\\";
rootPath=rootPath+"settings\\settings.config";
}
#endregion
if(!File.Exists(rootPath))
{
log.Write(MsgType.Fatal,"配置文件根目录rootPath为空");
returnnull;
}
stringcontent=File.ReadAllText(rootPath,Encoding.Default);
Class.Settingsmodel=PublicMethod.XmlSerialize.DeserializeXML<Class.Settings>(content);
log.Write(MsgType.Information,"读取配置文件");
CacheDependencycd=newCacheDependency(rootPath);
HttpRuntime.Cache.Add("settings",model,cd,DateTime.Now.AddMinutes(5),TimeSpan.Zero,CacheItemPriority.High,null);
returnmodel;
}
上面自动获取rootPath的方法:
///<summary>
///取当前根目录的方法
///</summary>
privatestaticstringGetPath()
{
stringrootPath="";
System.Diagnostics.Processp=System.Diagnostics.Process.GetCurrentProcess();
//WebDev.WebServervisualstudiowebserver
//xxx.vhostWinform
//w3wpIIS7
//aspnet_wpIIS6
//iisexpressvs2013
stringprocessName=p.ProcessName.ToLower();
if(processName=="aspnet_wp"||processName=="w3wp"||processName=="webdev.webserver"||processName=="iisexpress")
{
if(System.Web.HttpContext.Current!=null)
rootPath=System.Web.HttpContext.Current.Server.MapPath("~/");
else//当控件在定时器的触发程序中使用时就为空
{
rootPath=System.AppDomain.CurrentDomain.BaseDirectory;
}
}
returnrootPath;
}
Settings实体类的定义,要注意,这里的实体类要和settings配置文件对应,否则反序列化会出错:
[XmlRoot(Namespace="",IsNullable=false,ElementName="settings")]
publicclassSettings
{
#region属性
[XmlElement("logger")]
publicLoggerConfiglogger{get;set;}
#endregion
#region子类
[XmlType(TypeName="logger")]
publicclassLoggerConfig
{
publicstringloglevel{get;set;}
publicstringsavepath{get;set;}
}
#endregion
}
settings.config的内容实例
<?xmlversion='1.0'encoding='utf-8'?> <settings> <logger> <loglevel>0</loglevel> <savepath>d:\log</savepath> </logger> <queryurl>http://11.56.254.234:88/shashachaxunserver/shashachaxun</queryurl> <receiveurl>http://172.16.1.131:88/ThirdPay/ChinaUMS/xml.aspx</receiveurl> <turnurl>http://172.16.1.131:88/ThirdPay/ChinaUMS/query.aspx</turnurl> </chinaums> </settings>
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持毛票票!