using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Linq; using System.Runtime.Remoting; using System.Text; using System.Threading.Tasks; namespace XdCxRhDW.Framework { public static class AppConfigHelper { public static string Get(string key, string defaultVal = "") { var str = ConfigurationManager.AppSettings[key]; if (string.IsNullOrWhiteSpace(str)) return defaultVal; return str.Trim(); } public static string GetConnectionString(string name) { var str= ConfigurationManager.ConnectionStrings[name].ConnectionString.Trim(); if (!str.EndsWith(";")) str = $"{str};"; return str; } /// /// 获取App.config配置文件中appSettings节点中指定key的value /// 如果泛型为bool,则{"1","true","True","TRUE"}都会被转换成true,否则转换为false /// 该方法支持int?、double?等可空类型的转换 /// /// /// /// /// public static T Get(string key, T defaultVal = default) { var str = ConfigurationManager.AppSettings[key]; if (string.IsNullOrWhiteSpace(str)) { return defaultVal; } str = str.Trim(); bool isNullable = typeof(T).IsGenericType && typeof(T).GetGenericTypeDefinition() == typeof(Nullable<>); if (isNullable) { NullableConverter nullableConverter = new NullableConverter(typeof(T)); return (T)nullableConverter.ConvertFromString(str); } else if (typeof(T) == typeof(bool)) { if (str.ToLower().Trim() == "true" || str.ToLower().Trim() == "1") { T boolVal = (T)Convert.ChangeType(true, typeof(T)); return boolVal; } else { T boolVal = (T)Convert.ChangeType(false, typeof(T)); return boolVal; } } else { T ret = (T)Convert.ChangeType(str, typeof(T)); return ret; } } /// /// 如果参数小于0则返回0,否则返回原数字 /// /// /// public static int NotLessThanZero(this int @this) { if (@this >= 0) return @this; return 0; } /// /// 为url字符串添加后缀 /// /// /// /// public static string AppendUrlSuffix(this string @this, string suffix) { if (suffix.StartsWith("/")) suffix = suffix.Substring(1); if (@this.EndsWith("/")) return $"{@this}{suffix}"; else return $"{@this}/{suffix}"; } } }