WebExtension.cs 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. using Masuit.Tools.Core.Config;
  2. using Masuit.Tools.Models;
  3. using Microsoft.AspNetCore.Http;
  4. using Newtonsoft.Json;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Linq;
  8. using System.Net.Http;
  9. using System.Threading.Tasks;
  10. namespace Masuit.Tools.Core.Net
  11. {
  12. /// <summary>
  13. /// Web操作扩展
  14. /// </summary>
  15. public static class WebExtension
  16. {
  17. #region 获取客户端IP地址信息
  18. /// <summary>
  19. /// 根据IP地址获取详细地理信息
  20. /// </summary>
  21. /// <param name="ip"></param>
  22. /// <returns></returns>
  23. public static async Task<Tuple<string, List<string>>> GetIPAddressInfo(this string ip)
  24. {
  25. ip.MatchInetAddress(out var isIpAddress);
  26. if (isIpAddress)
  27. {
  28. var address = await GetPhysicsAddressInfo(ip);
  29. if (address.Status == 0)
  30. {
  31. string detail = $"{address.AddressResult.FormattedAddress} {address.AddressResult.AddressComponent.Direction}{address.AddressResult.AddressComponent.Distance ?? "0"}米";
  32. List<string> pois = address.AddressResult.Pois.Select(p => $"{p.AddressDetail}{p.Name} {p.Direction}{p.Distance ?? "0"}米").ToList();
  33. return new Tuple<string, List<string>>(detail, pois);
  34. }
  35. return new Tuple<string, List<string>>("IP地址不正确", new List<string>());
  36. }
  37. return new Tuple<string, List<string>>($"{ip}不是一个合法的IP地址", new List<string>());
  38. }
  39. /// <summary>
  40. /// 根据IP地址获取详细地理信息对象
  41. /// </summary>
  42. /// <param name="ip"></param>
  43. /// <returns></returns>
  44. public static async Task<PhysicsAddress> GetPhysicsAddressInfo(this string ip)
  45. {
  46. ip.MatchInetAddress(out var isIpAddress);
  47. if (isIpAddress)
  48. {
  49. string ak = CoreConfig.Configuration["BaiduAK"];
  50. if (string.IsNullOrEmpty(ak))
  51. {
  52. throw new Exception("未配置BaiduAK,请先在您的应用程序appsettings.json中下添加BaiduAK配置节(注意大小写)");
  53. }
  54. using (HttpClient client = new HttpClient() { BaseAddress = new Uri("http://api.map.baidu.com") })
  55. {
  56. client.DefaultRequestHeaders.Referrer = new Uri("http://lbsyun.baidu.com/jsdemo.htm");
  57. var task = client.GetAsync($"/location/ip?ak={ak}&ip={ip}&coor=bd09ll").ContinueWith(async t =>
  58. {
  59. if (t.IsFaulted || t.IsCanceled)
  60. {
  61. return null;
  62. }
  63. var res = await t;
  64. if (res.IsSuccessStatusCode)
  65. {
  66. var ipAddress = JsonConvert.DeserializeObject<BaiduIP>(await res.Content.ReadAsStringAsync());
  67. if (ipAddress.Status == 0)
  68. {
  69. LatiLongitude point = ipAddress.AddressInfo.LatiLongitude;
  70. string result = client.GetStringAsync($"/geocoder/v2/?location={point.Y},{point.X}&output=json&pois=1&radius=1000&latest_admin=1&coordtype=bd09ll&ak={ak}").Result;
  71. PhysicsAddress address = JsonConvert.DeserializeObject<PhysicsAddress>(result);
  72. if (address.Status == 0)
  73. {
  74. return address;
  75. }
  76. }
  77. else
  78. {
  79. using (var client2 = new HttpClient { BaseAddress = new Uri("http://ip.taobao.com") })
  80. {
  81. return await await client2.GetAsync($"/service/getIpInfo.php?ip={ip}").ContinueWith(async tt =>
  82. {
  83. if (tt.IsFaulted || tt.IsCanceled)
  84. {
  85. return null;
  86. }
  87. var result = await tt;
  88. if (result.IsSuccessStatusCode)
  89. {
  90. TaobaoIP taobaoIp = JsonConvert.DeserializeObject<TaobaoIP>(await result.Content.ReadAsStringAsync());
  91. if (taobaoIp.Code == 0)
  92. {
  93. return new PhysicsAddress()
  94. {
  95. Status = 0,
  96. AddressResult = new AddressResult()
  97. {
  98. FormattedAddress = taobaoIp.IpData.Country + taobaoIp.IpData.Region + taobaoIp.IpData.City,
  99. AddressComponent = new AddressComponent()
  100. {
  101. Province = taobaoIp.IpData.Region
  102. },
  103. Pois = new List<Pois>()
  104. }
  105. };
  106. }
  107. }
  108. return null;
  109. });
  110. }
  111. }
  112. }
  113. return null;
  114. });
  115. return await await task;
  116. }
  117. }
  118. return null;
  119. }
  120. /// <summary>
  121. /// 根据IP地址获取ISP
  122. /// </summary>
  123. /// <param name="ip"></param>
  124. /// <returns></returns>
  125. public static string GetISP(this string ip)
  126. {
  127. if (ip.MatchInetAddress())
  128. {
  129. using (var client = new HttpClient { BaseAddress = new Uri("http://ip.taobao.com") })
  130. {
  131. var task = client.GetAsync($"/service/getIpInfo.php?ip={ip}").ContinueWith(async t =>
  132. {
  133. if (t.IsFaulted)
  134. {
  135. return $"未能找到{ip}的ISP信息";
  136. }
  137. var result = await t;
  138. if (result.IsSuccessStatusCode)
  139. {
  140. TaobaoIP taobaoIp = JsonConvert.DeserializeObject<TaobaoIP>(await result.Content.ReadAsStringAsync());
  141. if (taobaoIp.Code == 0)
  142. {
  143. return taobaoIp.IpData.Isp;
  144. }
  145. }
  146. return $"未能找到{ip}的ISP信息";
  147. });
  148. return task.Result.Result;
  149. }
  150. }
  151. return $"{ip}不是一个合法的IP";
  152. }
  153. #endregion
  154. /// <summary>
  155. /// 写Session
  156. /// </summary>
  157. /// <param name="session"></param>
  158. /// <param name="key">键</param>
  159. /// <param name="value">值</param>
  160. public static void Set(this ISession session, string key, object value)
  161. {
  162. session.SetString(key, value.ToJsonString());
  163. }
  164. /// <summary>
  165. /// 获取Session
  166. /// </summary>
  167. /// <typeparam name="T">对象</typeparam>
  168. /// <param name="session"></param>
  169. /// <param name="key">键</param>
  170. /// <returns>对象</returns>
  171. public static T Get<T>(this ISession session, string key)
  172. {
  173. string value = session.GetString(key);
  174. if (string.IsNullOrEmpty(value))
  175. {
  176. return default;
  177. }
  178. return JsonConvert.DeserializeObject<T>(value);
  179. }
  180. }
  181. }