为了不使自己写的代码看着臃肿,有些固定的值抽取出来,放入配置文件里,这样,不失为一种好的编码习惯。这里介绍两种不同的文件格式:
一、AppSetting.config(.config格式)
1、首先,配置一下
1 <?xml version="1.0" encoding="utf-8"?> 2 <appSettings> 3 <!--纠错信息处理状态--> 4 <add key="CorrectState" value="已处理:0;未处理:1" /> 5 <!--调用接口 地址配制--> 6 <add key="Api_BaseUrl" value="http://172.16.16.68:8321/"/> 7 </appSettings>
2、读取唯一值
1 /// <summary> 2 /// 通过key,获取appSetting的值 3 /// </summary> 4 /// <param name="key">key</param> 5 /// <returns>value</returns> 6 public static string GetWebConfigValueByKey(string key) 7 { 8 string value = string.Empty; 9 Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath); 10 AppSettingsSection appSetting = (AppSettingsSection)config.GetSection("appSettings"); 11 if (appSetting.Settings[key] != null)//如果不存在此节点,则添加 12 { 13 value = appSetting.Settings[key].Value; 14 } 15 config = null; 16 return value; 17 }
3、读取多个值
1 /// <summary> 2 /// 如果值为 "已审核:1;待审核:0" 形式 ,可通过该函数获取该appsetting值的指定value对应的key 3 /// </summary> 4 /// <param name="appSettingName"></param> 5 /// <returns></returns> 6 public static string GetKVofKey(string appSettingName, string value) 7 { 8 List<KV> l = new List<KV>(); 9 string str = GetWebConfigValueByKey(appSettingName); 10 string[] arr = str.Split(';'); 11 string rs = ""; 12 if (arr.Length > 0) 13 { 14 int length = arr.Length; 15 for (int i = 0; i < length; i++) 16 { 17 if (arr[i].Split(':')[1] == value) 18 { 19 rs = arr[i].Split(':')[0]; 20 } 21 } 22 } 23 return rs; 24 }
所用类
1 1 public class KV 2 2 { 3 3 public string k; 4 4 public string v; 5 5 }
二、Api.ini
1、配置文件
1 #微信支付 2 [WeiXinPay] 3 appId=wx1***1 4 partnerid=1***1 5 appSecret=6***5 6 key=N**C
2、ApiHelper.cs(类)
1 public class ApiHelper 2 { 3 /// <summary> 4 /// 配置文件虚拟路径 5 /// </summary> 6 private const string ConfigFile = "~/Config/Api.ini"; 7 /// <summary> 8 /// 获取配置节 9 /// </summary> 10 /// <typeparam name="T">节点类型(引用类型)</typeparam> 11 /// <param name="section">节点名称</param> 12 /// <returns></returns> 13 public static T GetConfigureSection<T>(string section) 14 where T:class 15 { 16 SharpConfig.Configuration configuration = GetIniConfiguration(); 17 return configuration[section].CreateObject<T>(); 18 } 19 public static string GetPath(string path) 20 { 21 if (HttpContext.Current !=null) 22 { 23 return HttpContext.Current.Server.MapPath(path); 24 } 25 path = path.Replace("/","\"); 26 if (path.StartsWith("\")) 27 { 28 path = path.Substring(path.IndexOf('\', 1)).TrimStart('\'); 29 } 30 return Path.Combine(AppDomain.CurrentDomain.BaseDirectory,path); 31 } 32 /// <summary> 33 /// 34 /// </summary> 35 /// <returns></returns> 36 public static SharpConfig.Configuration GetIniConfiguration() 37 { 38 const string SYSTEM_API_CONFIG = "SYSTEM_API_CONFIG";//配置Key 39 //如果缓存存在,则提取缓存数据 40 if (RuntimeCacheHelper.IsExists(SYSTEM_API_CONFIG)) 41 { 42 return RuntimeCacheHelper.Get<SharpConfig.Configuration>(SYSTEM_API_CONFIG); 43 } 44 //从配置文件中加载,并缓存配置 45 else 46 { 47 SharpConfig.Configuration configuration = null; 48 String strConfigAbsolutePath = GetPath(ConfigFile); 49 configuration = SharpConfig.Configuration.LoadFromFile(strConfigAbsolutePath); 50 //缓存对象 51 RuntimeCacheHelper.Save(SYSTEM_API_CONFIG,configuration,strConfigAbsolutePath,new TimeSpan(365,0,0,0,0)); 52 return configuration; 53 } 54 } 55 }
缓存类
1 public class RuntimeCacheHelper 2 { 3 public static bool IsExists(string Name) 4 { 5 return (HttpRuntime.Cache[Name] != null); 6 } 7 public static T Get<T>(string Name) 8 { 9 if (null != HttpRuntime.Cache[Name]) { return (T)HttpRuntime.Cache[Name]; } 10 return default(T); 11 } 12 13 public static void Save(string Name, object Value, string FileName, TimeSpan expirese) 14 { 15 var dependency = new CacheDependency(FileName); 16 Save(Name, 17 Value, 18 dependency, 19 expirese); 20 } 21 22 public static void Save(string Name, object Value) 23 { 24 HttpRuntime.Cache.Insert(Name, Value); 25 } 26 27 public static void Save(string Name, object Value, CacheDependency Dependency, TimeSpan expirese) 28 { 29 HttpRuntime.Cache.Insert(Name, 30 Value, 31 Dependency, 32 (DateTime.Now + expirese), 33 System.Web.Caching.Cache.NoSlidingExpiration); 34 } 35 }
3、请求上下文(HttpContextExtension)类
1 public static class HttpContextExtension 2 { 3 /// <summary> 4 /// 请求上下文 5 /// </summary> 6 /// <param name="context"></param> 7 /// <returns></returns> 8 public static WeiXinPayConfig GetWeiXinPayConfig(this HttpContextBase context) 9 { 10 return ApiHelper.GetConfigureSection<WeiXinPayConfig>("WeiXinPay"); 11 } 12 }
4、获取值
1 /// <summary> 2 /// 3 /// </summary> 4 private Models.WeiXinPayConfig wxApiConfig { get; set; } 5 /// <summary> 6 /// 7 /// </summary> 8 /// <returns></returns> 9 public ActionResult GetConfig() 10 { 11 12 wxApiConfig = HttpContext.GetWeiXinPayConfig(); 13 14 return View(); 15 }