Utility.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Globalization;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Net.Security;
  9. using System.Security.Cryptography.X509Certificates;
  10. using System.Text;
  11. using System.Text.RegularExpressions;
  12. using System.Web;
  13. namespace CZFW.Core
  14. {
  15. public class Utility
  16. {
  17. public static TType Parse<TType>(object value, TType defaultValue = default(TType))
  18. {
  19. if (value == null || value == DBNull.Value || string.IsNullOrWhiteSpace(value.ToString())) return defaultValue;
  20. Type type = typeof(TType);
  21. Type underlyingType = Nullable.GetUnderlyingType(type);
  22. return (TType)Convert.ChangeType(value, underlyingType ?? type);
  23. }
  24. public static long GetUnixTimeTick(DateTime? date = null)
  25. {
  26. if (date == null)
  27. {
  28. date = DateTime.Now;
  29. }
  30. var timespan = date.Value.Subtract(new DateTime(1970, 1, 1));
  31. return timespan.Ticks;
  32. }
  33. public static string GetNowStringForSql(DateTime? dateTime = null, string format = "yyyy/MM/dd hh:mm:ss")
  34. {
  35. var now = dateTime is null ? DateTime.Now : dateTime.Value;
  36. var nowStr = now.ToString(format);
  37. var res = $"'{nowStr}'";
  38. return res;
  39. }
  40. #region Get
  41. /// <summary>
  42. /// HTTP GET方式请求数据.
  43. /// </summary>
  44. /// <param name="url">URL.</param>
  45. /// <param name="headht"></param>
  46. /// <returns></returns>
  47. public static string HttpGet(string url, Hashtable headht = null)
  48. {
  49. HttpWebRequest request;
  50. //如果是发送HTTPS请求
  51. if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
  52. {
  53. ServicePointManager.ServerCertificateValidationCallback = CheckValidationResult;
  54. request = WebRequest.Create(url) as HttpWebRequest;
  55. request.ProtocolVersion = HttpVersion.Version10;
  56. }
  57. else
  58. {
  59. request = WebRequest.Create(url) as HttpWebRequest;
  60. }
  61. request.Method = "GET";
  62. //request.ContentType = "application/x-www-form-urlencoded";
  63. request.Accept = "*/*";
  64. request.Timeout = 15000;
  65. request.AllowAutoRedirect = false;
  66. string responseStr;
  67. if (headht != null)
  68. {
  69. foreach (DictionaryEntry item in headht)
  70. {
  71. request.Headers.Add(item.Key.ToString(), item.Value.ToString());
  72. }
  73. }
  74. var response = request.GetResponse();
  75. {
  76. StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  77. responseStr = reader.ReadToEnd();
  78. reader.Close();
  79. }
  80. return responseStr;
  81. }
  82. public static string HttpGet(string url, Encoding encodeing, Hashtable headht = null)
  83. {
  84. HttpWebRequest request;
  85. //如果是发送HTTPS请求
  86. if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
  87. {
  88. ServicePointManager.ServerCertificateValidationCallback = CheckValidationResult;
  89. request = WebRequest.Create(url) as HttpWebRequest;
  90. request.ProtocolVersion = HttpVersion.Version10;
  91. }
  92. else
  93. {
  94. request = WebRequest.Create(url) as HttpWebRequest;
  95. }
  96. request.Method = "GET";
  97. //request.ContentType = "application/x-www-form-urlencoded";
  98. request.Accept = "*/*";
  99. request.Timeout = 15000;
  100. request.AllowAutoRedirect = false;
  101. string responseStr;
  102. if (headht != null)
  103. {
  104. foreach (DictionaryEntry item in headht)
  105. {
  106. request.Headers.Add(item.Key.ToString(), item.Value.ToString());
  107. }
  108. }
  109. var response = request.GetResponse();
  110. {
  111. StreamReader reader = new StreamReader(response.GetResponseStream(), encodeing);
  112. responseStr = reader.ReadToEnd();
  113. reader.Close();
  114. }
  115. return responseStr;
  116. }
  117. #endregion
  118. private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
  119. {
  120. return true; //总是接受
  121. }
  122. public static bool IsMobile(string userAgent)
  123. {
  124. string u = userAgent;
  125. Regex b = new Regex(@"(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|WindowsWechat", RegexOptions.IgnoreCase | RegexOptions.Multiline);
  126. Regex v = new Regex(@"1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-", RegexOptions.IgnoreCase | RegexOptions.Multiline);
  127. var res = b.IsMatch(u) || v.IsMatch(u.Substring(0, 4));
  128. return res;
  129. }
  130. public static bool IsWeChat(string userAgent)
  131. {
  132. if (userAgent == null)
  133. return false;
  134. return userAgent.ToLower().Contains("micromessenger");
  135. }
  136. public static (string fullBroswerName, string browserName, string ver) GetBrowserName(string userAgent)
  137. {
  138. string fullBrowserName, browserName, ver;
  139. browserName = string.Empty;
  140. ver = string.Empty;
  141. fullBrowserName = string.Empty;
  142. // IE
  143. string regexStr = @"msie (?<ver>[\d.]+)";
  144. Regex r = new Regex(regexStr, RegexOptions.IgnoreCase);
  145. Match m = r.Match(userAgent);
  146. if (m.Success)
  147. {
  148. browserName = "IE";
  149. ver = m.Groups["ver"].Value;
  150. fullBrowserName = string.Format("{0} {1}", browserName, ver);
  151. return (fullBrowserName, browserName, ver);
  152. }
  153. // Firefox
  154. regexStr = @"firefox\/([\d.]+)";
  155. r = new Regex(regexStr, RegexOptions.IgnoreCase);
  156. m = r.Match(userAgent);
  157. if (m.Success)
  158. {
  159. browserName = "IE";
  160. ver = m.Groups["ver"].Value;
  161. fullBrowserName = string.Format("{0} {1}", browserName, ver);
  162. return (fullBrowserName, browserName, ver);
  163. }
  164. // Chrome
  165. regexStr = @"chrome\/([\d.]+)";
  166. r = new Regex(regexStr, RegexOptions.IgnoreCase);
  167. m = r.Match(userAgent);
  168. if (m.Success)
  169. {
  170. browserName = "IE";
  171. ver = m.Groups["ver"].Value;
  172. fullBrowserName = string.Format("{0} {1}", browserName, ver);
  173. return (fullBrowserName, browserName, ver);
  174. }
  175. // Opera
  176. regexStr = @"opera.([\d.]+)";
  177. r = new Regex(regexStr, RegexOptions.IgnoreCase);
  178. m = r.Match(userAgent);
  179. if (m.Success)
  180. {
  181. browserName = "IE";
  182. ver = m.Groups["ver"].Value;
  183. fullBrowserName = string.Format("{0} {1}", browserName, ver);
  184. return (fullBrowserName, browserName, ver);
  185. }
  186. // Safari
  187. regexStr = @"version\/([\d.]+).*safari";
  188. r = new Regex(regexStr, RegexOptions.IgnoreCase);
  189. m = r.Match(userAgent);
  190. if (m.Success)
  191. {
  192. browserName = "IE";
  193. ver = m.Groups["ver"].Value;
  194. fullBrowserName = string.Format("{0} {1}", browserName, ver);
  195. return (fullBrowserName, browserName, ver);
  196. }
  197. return (fullBrowserName, browserName, ver);
  198. }
  199. public static string GetOSNameByUserAgent(string userAgent)
  200. {
  201. string osVersion = "未知";
  202. if (userAgent.Contains("NT 10.0"))
  203. {
  204. osVersion = "Windows 10";
  205. }
  206. else if (userAgent.Contains("NT 6.3"))
  207. {
  208. osVersion = "Windows 8.1";
  209. }
  210. else if (userAgent.Contains("NT 6.2"))
  211. {
  212. osVersion = "Windows 8";
  213. }
  214. else if (userAgent.Contains("NT 6.1"))
  215. {
  216. osVersion = "Windows 7";
  217. }
  218. else if (userAgent.Contains("NT 6.1"))
  219. {
  220. osVersion = "Windows 7";
  221. }
  222. else if (userAgent.Contains("NT 6.0"))
  223. {
  224. osVersion = "Windows Vista/Server 2008";
  225. }
  226. else if (userAgent.Contains("NT 5.2"))
  227. {
  228. if (userAgent.Contains("64"))
  229. osVersion = "Windows XP";
  230. else
  231. osVersion = "Windows Server 2003";
  232. }
  233. else if (userAgent.Contains("NT 5.1"))
  234. {
  235. osVersion = "Windows XP";
  236. }
  237. else if (userAgent.Contains("NT 5"))
  238. {
  239. osVersion = "Windows 2000";
  240. }
  241. else if (userAgent.Contains("NT 4"))
  242. {
  243. osVersion = "Windows NT4";
  244. }
  245. else if (userAgent.Contains("Me"))
  246. {
  247. osVersion = "Windows Me";
  248. }
  249. else if (userAgent.Contains("98"))
  250. {
  251. osVersion = "Windows 98";
  252. }
  253. else if (userAgent.Contains("95"))
  254. {
  255. osVersion = "Windows 95";
  256. }
  257. else if (userAgent.Contains("Mac"))
  258. {
  259. osVersion = "Mac";
  260. }
  261. else if (userAgent.Contains("Unix"))
  262. {
  263. osVersion = "UNIX";
  264. }
  265. else if (userAgent.Contains("Linux"))
  266. {
  267. osVersion = "Linux";
  268. }
  269. else if (userAgent.Contains("SunOS"))
  270. {
  271. osVersion = "SunOS";
  272. }
  273. return osVersion;
  274. }
  275. public static Tuple<string, IDictionary<string, string>> UrlToData(string url, string encoding = "UTF-8")
  276. {
  277. var res = new Tuple<string, IDictionary<string, string>>(string.Empty, new Dictionary<string, string>());
  278. if (string.IsNullOrWhiteSpace(url))
  279. {
  280. throw new ArgumentNullException($"UrlToData时URL格式错误, URL:{url}");
  281. }
  282. url = url.Trim();
  283. if (url.Contains("%"))
  284. {
  285. url = UrlDecode(url, encoding);
  286. }
  287. var uri = new Uri(url);
  288. var split = uri.Query.Split(new[] { '?', '&' }, StringSplitOptions.RemoveEmptyEntries);
  289. if (split.Length == 1)
  290. return new Tuple<string, IDictionary<string, string>>(url, new Dictionary<string, string>());
  291. //获取前面的URL地址
  292. var host = uri.Host;
  293. var paras = split.ToList();
  294. var pairs = new Dictionary<string, string>();
  295. foreach (var s in paras)
  296. {
  297. var idx = s.IndexOf('=');
  298. if (idx > 0)
  299. {
  300. if (!pairs.ContainsKey(Uri.UnescapeDataString(s.Substring(0, idx))))
  301. pairs.Add(Uri.UnescapeDataString(s.Substring(0, idx)), Uri.UnescapeDataString(s.Substring(idx + 1)));
  302. }
  303. }
  304. res = new Tuple<string, IDictionary<string, string>>(host, pairs);
  305. return res;
  306. }
  307. public static string UrlDecode(string str, string encoding = "UTF-8")
  308. {
  309. var res = HttpUtility.UrlDecode(str, Encoding.GetEncoding(encoding));
  310. res = res.Replace("\u0001", "");
  311. return res;
  312. }
  313. public static bool CheckMobileNumber(string phoneNumber)
  314. {
  315. if (string.IsNullOrWhiteSpace(phoneNumber))
  316. return false;
  317. return System.Text.RegularExpressions.Regex.IsMatch(phoneNumber, @"^[1]+[3,4,5,7,8]+\d{9}");
  318. }
  319. }
  320. }