소스 검색

获取ip信息优化

懒得勤快 4 년 전
부모
커밋
4210c3f9bb

+ 1 - 1
Masuit.Tools.Abstractions/Masuit.Tools.Abstractions.csproj

@@ -51,7 +51,6 @@
     <PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
     <PackageReference Include="System.ComponentModel.Annotations" Version="4.7.0" />
     <PackageReference Include="System.Diagnostics.PerformanceCounter" Version="4.7.0" />
-    <PackageReference Include="System.Drawing.Common" Version="4.7.0" />
     <PackageReference Include="System.Management" Version="4.7.0" />
     <PackageReference Include="System.Reflection.Emit.Lightweight" Version="4.7.0" />
   </ItemGroup>
@@ -65,6 +64,7 @@
   <ItemGroup Condition=" '$(TargetFramework)' == 'netstandard2.1'">
     <PackageReference Include="Microsoft.AspNetCore.Http.Extensions" Version="2.2.0" />
     <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="3.1.9" />
+    <PackageReference Include="System.Drawing.Common" Version="5.0.0" />
   </ItemGroup>
 
   <ItemGroup Condition=" '$(TargetFramework)' == 'net5'">

+ 13 - 25
Masuit.Tools.Core/Masuit.Tools.Core.csproj

@@ -356,42 +356,30 @@
         <PackageReference Include="HtmlAgilityPack" Version="1.11.29" />
         <PackageReference Include="HtmlSanitizer" Version="5.0.355" />
         <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0" />
-        <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0" PrivateAssets="All" />
-        <PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
-        <!--<PackageReference Include="System.Reflection.Emit" Version="4.7.0" />-->
-        <PackageReference Include="System.Reflection.Emit.Lightweight" Version="4.7.0" />
-        <PackageReference Include="SharpCompress" Version="0.26.0" />
-    </ItemGroup>
-
-    <ItemGroup Condition=" '$(TargetFramework)' == 'net5'">
-        <PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.1" />
         <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="5.0" />
         <PackageReference Include="Microsoft.Extensions.Http" Version="5.0" />
+        <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0" PrivateAssets="All" />
         <PackageReference Include="Microsoft.Win32.Registry" Version="5.0" />
+        <PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
+        <!--<PackageReference Include="System.Reflection.Emit" Version="4.7.0" />-->
         <PackageReference Include="System.ComponentModel.Annotations" Version="5.0" />
-        <PackageReference Include="System.Diagnostics.PerformanceCounter" Version="5.0" />
         <PackageReference Include="System.Drawing.Common" Version="5.0" />
+        <PackageReference Include="System.Diagnostics.PerformanceCounter" Version="5.0" />
         <PackageReference Include="System.Management" Version="5.0" />
+        <PackageReference Include="System.Reflection.Emit.Lightweight" Version="4.7.0" />
+        <PackageReference Include="SharpCompress" Version="0.26.0" />
     </ItemGroup>
-    <ItemGroup Condition=" '$(TargetFramework)' == 'netstandard2.1'">
-        <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.9" />
-        <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="3.1.9" />
-        <PackageReference Include="Microsoft.Extensions.Http" Version="3.1.9" />
-        <PackageReference Include="Microsoft.Win32.Registry" Version="4.7.0" />
-        <PackageReference Include="System.ComponentModel.Annotations" Version="4.7.0" />
-        <PackageReference Include="System.Diagnostics.PerformanceCounter" Version="4.7.0" />
-        <PackageReference Include="System.Drawing.Common" Version="4.7.0" />
-        <PackageReference Include="System.Management" Version="4.7.0" />
-    </ItemGroup>
+
     <ItemGroup Condition=" '$(TargetFramework)' == 'netstandard2.0'">
         <PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.2.6" />
         <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.2.0" />
         <PackageReference Include="Microsoft.Extensions.Http" Version="2.2.0" />
-        <PackageReference Include="Microsoft.Win32.Registry" Version="4.7.0" />
-        <PackageReference Include="System.ComponentModel.Annotations" Version="4.7.0" />
-        <PackageReference Include="System.Diagnostics.PerformanceCounter" Version="4.7.0" />
-        <PackageReference Include="System.Drawing.Common" Version="4.7.0" />
-        <PackageReference Include="System.Management" Version="4.7.0" />
+    </ItemGroup>
+    <ItemGroup Condition=" '$(TargetFramework)' == 'netstandard2.1'">
+        <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.9" />
+    </ItemGroup>
+    <ItemGroup Condition=" '$(TargetFramework)' == 'net5'">
+        <PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.1" />
     </ItemGroup>
     <ItemGroup>
         <None Update="Masuit.Tools.Core.xml">

+ 61 - 63
Masuit.Tools.Core/Net/WebExtension.cs

@@ -7,6 +7,7 @@ using System.Collections.Generic;
 using System.Linq;
 using System.Linq.Expressions;
 using System.Net.Http;
+using System.Threading;
 using System.Threading.Tasks;
 
 namespace Masuit.Tools.Core.Net
@@ -37,6 +38,7 @@ namespace Masuit.Tools.Core.Net
         }
 
         private static readonly HttpClient HttpClient = new HttpClient();
+        private static readonly CancellationTokenSource _cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
 
         /// <summary>
         /// 根据IP地址获取详细地理信息对象
@@ -52,66 +54,65 @@ namespace Masuit.Tools.Core.Net
 
             var ak = ConfigHelper.GetConfigOrDefault("BaiduAK", null) ?? throw new Exception("未配置BaiduAK,请先在您的应用程序appsettings.json中下添加BaiduAK配置节(注意大小写);或手动在程序入口处调用IConfiguration的AddToMasuitTools方法");
             HttpClient.DefaultRequestHeaders.Referrer = new Uri("http://lbsyun.baidu.com/jsdemo.htm");
-            var task = HttpClient.GetAsync($"http://api.map.baidu.com/location/ip?ak={ak}&ip={ip}&coor=bd09ll").ContinueWith(async t =>
+            var ipAddress = await HttpClient.GetAsync($"http://api.map.baidu.com/location/ip?ak={ak}&ip={ip}&coor=bd09ll", _cts.Token).ContinueWith(t =>
             {
-                if (t.IsFaulted || t.IsCanceled)
+                if (t.IsCompleted && t.Result.IsSuccessStatusCode)
                 {
-                    return null;
-                }
-                var res = await t;
-                if (!res.IsSuccessStatusCode)
-                {
-                    return null;
+                    using var content = t.Result.Content;
+                    return JsonConvert.DeserializeObject<BaiduIP>(content.ReadAsStringAsync().Result);
                 }
 
-                var ipAddress = JsonConvert.DeserializeObject<BaiduIP>(await res.Content.ReadAsStringAsync());
-                if (ipAddress.Status == 0)
+                return null;
+            });
+            if (ipAddress?.Status == 0)
+            {
+                var point = ipAddress.AddressInfo.LatiLongitude;
+                var result = await HttpClient.GetAsync($"http://api.map.baidu.com/geocoder/v2/?location={point.Y},{point.X}&output=json&pois=1&radius=1000&latest_admin=1&coordtype=bd09ll&ak={ak}", _cts.Token).ContinueWith(tt =>
                 {
-                    var point = ipAddress.AddressInfo.LatiLongitude;
-                    var result = HttpClient.GetStringAsync($"http://api.map.baidu.com/geocoder/v2/?location={point.Y},{point.X}&output=json&pois=1&radius=1000&latest_admin=1&coordtype=bd09ll&ak={ak}").Result;
-                    var address = JsonConvert.DeserializeObject<PhysicsAddress>(result);
-                    if (address.Status == 0)
+                    if (tt.IsCompleted && tt.Result.IsSuccessStatusCode)
                     {
-                        return address;
+                        using var content = tt.Result.Content;
+                        return JsonConvert.DeserializeObject<PhysicsAddress>(content.ReadAsStringAsync().Result);
                     }
+
+                    return null;
+                });
+                if (result?.Status == 0)
+                {
+                    return result;
                 }
-                else
+            }
+            else
+            {
+                var taobaoIp = await HttpClient.GetAsync($"http://ip.taobao.com/service/getIpInfo.php?ip={ip}", _cts.Token).ContinueWith(tt =>
                 {
-                    return await HttpClient.GetAsync($"http://ip.taobao.com/service/getIpInfo.php?ip={ip}").ContinueWith(tt =>
+                    if (tt.IsCompleted && tt.Result.IsSuccessStatusCode)
                     {
-                        if (tt.IsFaulted || tt.IsCanceled)
-                        {
-                            return null;
-                        }
-                        var result = tt.Result;
-                        if (!result.IsSuccessStatusCode)
-                        {
-                            return null;
-                        }
+                        using var content = tt.Result.Content;
+                        return JsonConvert.DeserializeObject<TaobaoIP>(content.ReadAsStringAsync().Result);
+                    }
 
-                        var taobaoIp = JsonConvert.DeserializeObject<TaobaoIP>(result.Content.ReadAsStringAsync().Result);
-                        if (taobaoIp.Code == 0)
+                    return null;
+                });
+                if (taobaoIp?.Code == 0)
+                {
+                    return new PhysicsAddress()
+                    {
+                        Status = 0,
+                        AddressResult = new AddressResult()
                         {
-                            return new PhysicsAddress()
+                            FormattedAddress = taobaoIp.IpData.Country + taobaoIp.IpData.Region + taobaoIp.IpData.City,
+                            AddressComponent = new AddressComponent()
                             {
-                                Status = 0,
-                                AddressResult = new AddressResult()
-                                {
-                                    FormattedAddress = taobaoIp.IpData.Country + taobaoIp.IpData.Region + taobaoIp.IpData.City,
-                                    AddressComponent = new AddressComponent()
-                                    {
-                                        Province = taobaoIp.IpData.Region
-                                    },
-                                    Pois = new List<Pois>()
-                                }
-                            };
+                                Province = taobaoIp.IpData.Region
+                            },
+                            Pois = new List<Pois>()
                         }
-                        return null;
-                    });
+                    };
                 }
-                return null;
-            });
-            return await await task;
+            }
+
+            return null;
         }
 
         /// <summary>
@@ -126,24 +127,21 @@ namespace Masuit.Tools.Core.Net
                 return $"{ip}不是一个合法的IP";
             }
 
-            var task = HttpClient.GetAsync($"http://ip.taobao.com/service/getIpInfo.php?ip={ip}").ContinueWith(async t =>
-            {
-                if (t.IsFaulted)
-                {
-                    return $"未能找到{ip}的ISP信息";
-                }
-                var result = await t;
-                if (result.IsSuccessStatusCode)
-                {
-                    var taobaoIp = JsonConvert.DeserializeObject<TaobaoIP>(await result.Content.ReadAsStringAsync());
-                    if (taobaoIp.Code == 0)
-                    {
-                        return taobaoIp.IpData.Isp;
-                    }
-                }
-                return $"未能找到{ip}的ISP信息";
-            });
-            return task.Result.Result;
+            var task = HttpClient.GetAsync($"http://ip.taobao.com/service/getIpInfo.php?ip={ip}", _cts.Token).ContinueWith(t =>
+             {
+                 if (t.IsCompleted)
+                 {
+                     using var content = t.Result.Content;
+                     var taobaoIp = JsonConvert.DeserializeObject<TaobaoIP>(content.ReadAsStringAsync().Result);
+                     if (taobaoIp.Code == 0)
+                     {
+                         return taobaoIp.IpData.Isp;
+                     }
+                 }
+
+                 return $"未能找到{ip}的ISP信息";
+             });
+            return task.Result;
         }
 
         #endregion 获取客户端IP地址信息

+ 72 - 103
Masuit.Tools/Net/WebExtension.cs

@@ -1,14 +1,15 @@
-using Masuit.Tools.Logging;
+using Masuit.Tools.Core.Config;
+using Masuit.Tools.Logging;
 using Masuit.Tools.Models;
 using Masuit.Tools.NoSQL;
 using Masuit.Tools.Security;
 using Newtonsoft.Json;
 using System;
 using System.Collections.Generic;
-using System.Configuration;
 using System.Linq;
 using System.Net.Http;
 using System.Runtime.Remoting.Messaging;
+using System.Threading;
 using System.Threading.Tasks;
 using System.Web;
 using System.Web.SessionState;
@@ -377,23 +378,20 @@ namespace Masuit.Tools.Net
         /// <returns></returns>
         public static async Task<Tuple<string, List<string>>> GetIPAddressInfo(this string ip)
         {
-            ip.MatchInetAddress(out var isIpAddress);
-            if (isIpAddress)
+            var address = await GetPhysicsAddressInfo(ip);
+            if (address?.Status == 0)
             {
-                var address = await GetPhysicsAddressInfo(ip);
-                if (address.Status == 0)
-                {
-                    string detail = $"{address.AddressResult.FormattedAddress} {address.AddressResult.AddressComponent.Direction}{address.AddressResult.AddressComponent.Distance ?? "0"}米";
-                    List<string> pois = address.AddressResult.Pois.Select(p => $"{p.AddressDetail}{p.Name} {p.Direction}{p.Distance ?? "0"}米").ToList();
-                    return new Tuple<string, List<string>>(detail, pois);
-                }
-
-                return new Tuple<string, List<string>>("IP地址不正确", new List<string>());
+                string detail = $"{address.AddressResult.FormattedAddress} {address.AddressResult.AddressComponent.Direction}{address.AddressResult.AddressComponent.Distance ?? "0"}米";
+                var pois = address.AddressResult.Pois.Select(p => $"{p.AddressDetail}{p.Name} {p.Direction}{p.Distance ?? "0"}米").ToList();
+                return new Tuple<string, List<string>>(detail, pois);
             }
 
-            return new Tuple<string, List<string>>($"{ip}不是一个合法的IP地址", new List<string>());
+            return new Tuple<string, List<string>>("IP地址不正确", new List<string>());
         }
 
+        private static readonly HttpClient HttpClient = new HttpClient();
+        private static readonly CancellationTokenSource _cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
+
         /// <summary>
         /// 根据IP地址获取详细地理信息对象
         /// </summary>
@@ -406,86 +404,67 @@ namespace Masuit.Tools.Net
                 return null;
             }
 
-            string ak = ConfigurationManager.AppSettings["BaiduAK"];
-            if (string.IsNullOrEmpty(ak))
-            {
-                throw new Exception("未配置BaiduAK,请先在您的应用程序web.config或者App.config中的AppSettings节点下添加BaiduAK配置节(注意大小写)");
-            }
-
-            using var client = new HttpClient()
+            var ak = ConfigHelper.GetConfigOrDefault("BaiduAK", null) ?? throw new Exception("未配置BaiduAK,请先在您的应用程序appsettings.json中下添加BaiduAK配置节(注意大小写);或手动在程序入口处调用IConfiguration的AddToMasuitTools方法");
+            HttpClient.DefaultRequestHeaders.Referrer = new Uri("http://lbsyun.baidu.com/jsdemo.htm");
+            var ipAddress = await HttpClient.GetAsync($"http://api.map.baidu.com/location/ip?ak={ak}&ip={ip}&coor=bd09ll", _cts.Token).ContinueWith(t =>
             {
-                BaseAddress = new Uri("http://api.map.baidu.com")
-            };
-            client.DefaultRequestHeaders.Referrer = new Uri("http://lbsyun.baidu.com/jsdemo.htm");
-            var task = client.GetAsync($"/location/ip?ak={ak}&ip={ip}&coor=bd09ll").ContinueWith(async t =>
-            {
-                if (t.IsFaulted || t.IsCanceled)
+                if (t.IsCompleted && t.Result.IsSuccessStatusCode)
                 {
-                    return null;
+                    using var content = t.Result.Content;
+                    return JsonConvert.DeserializeObject<BaiduIP>(content.ReadAsStringAsync().Result);
                 }
 
-                var res = await t;
-                if (!res.IsSuccessStatusCode)
+                return null;
+            });
+            if (ipAddress?.Status == 0)
+            {
+                var point = ipAddress.AddressInfo.LatiLongitude;
+                var result = await HttpClient.GetAsync($"http://api.map.baidu.com/geocoder/v2/?location={point.Y},{point.X}&output=json&pois=1&radius=1000&latest_admin=1&coordtype=bd09ll&ak={ak}", _cts.Token).ContinueWith(tt =>
                 {
+                    if (tt.IsCompleted && tt.Result.IsSuccessStatusCode)
+                    {
+                        using var content = tt.Result.Content;
+                        return JsonConvert.DeserializeObject<PhysicsAddress>(content.ReadAsStringAsync().Result);
+                    }
+
                     return null;
+                });
+                if (result?.Status == 0)
+                {
+                    return result;
                 }
-
-                var ipAddress = JsonConvert.DeserializeObject<BaiduIP>(await res.Content.ReadAsStringAsync());
-                if (ipAddress.Status == 0)
+            }
+            else
+            {
+                var taobaoIp = await HttpClient.GetAsync($"http://ip.taobao.com/service/getIpInfo.php?ip={ip}", _cts.Token).ContinueWith(tt =>
                 {
-                    var point = ipAddress.AddressInfo.LatiLongitude;
-                    var result = client.GetStringAsync($"/geocoder/v2/?location={point.Y},{point.X}&output=json&pois=1&radius=1000&latest_admin=1&coordtype=bd09ll&ak={ak}").Result;
-                    var address = JsonConvert.DeserializeObject<PhysicsAddress>(result);
-                    if (address.Status == 0)
+                    if (tt.IsCompleted && tt.Result.IsSuccessStatusCode)
                     {
-                        return address;
+                        using var content = tt.Result.Content;
+                        return JsonConvert.DeserializeObject<TaobaoIP>(content.ReadAsStringAsync().Result);
                     }
-                }
-                else
+
+                    return null;
+                });
+                if (taobaoIp?.Code == 0)
                 {
-                    using var client2 = new HttpClient
+                    return new PhysicsAddress()
                     {
-                        BaseAddress = new Uri("http://ip.taobao.com")
-                    };
-                    return await await client2.GetAsync($"/service/getIpInfo.php?ip={ip}").ContinueWith(async tt =>
-                    {
-                        if (tt.IsFaulted || tt.IsCanceled)
+                        Status = 0,
+                        AddressResult = new AddressResult()
                         {
-                            return null;
-                        }
-
-                        var result = await tt;
-                        if (!result.IsSuccessStatusCode)
-                        {
-                            return null;
-                        }
-
-                        var taobaoIp = JsonConvert.DeserializeObject<TaobaoIP>(await result.Content.ReadAsStringAsync());
-                        if (taobaoIp.Code == 0)
-                        {
-                            return new PhysicsAddress()
+                            FormattedAddress = taobaoIp.IpData.Country + taobaoIp.IpData.Region + taobaoIp.IpData.City,
+                            AddressComponent = new AddressComponent()
                             {
-                                Status = 0,
-                                AddressResult = new AddressResult()
-                                {
-                                    FormattedAddress = taobaoIp.IpData.Country + taobaoIp.IpData.Region + taobaoIp.IpData.City,
-                                    AddressComponent = new AddressComponent()
-                                    {
-                                        Province = taobaoIp.IpData.Region
-                                    },
-                                    Pois = new List<Pois>()
-                                }
-                            };
+                                Province = taobaoIp.IpData.Region
+                            },
+                            Pois = new List<Pois>()
                         }
-
-                        return null;
-                    });
+                    };
                 }
+            }
 
-                return null;
-            });
-            return await await task;
-
+            return null;
         }
 
         /// <summary>
@@ -500,33 +479,23 @@ namespace Masuit.Tools.Net
                 return $"{ip}不是一个合法的IP";
             }
 
-            using var client = new HttpClient
-            {
-                BaseAddress = new Uri("http://ip.taobao.com")
-            };
-            var task = client.GetAsync($"/service/getIpInfo.php?ip={ip}").ContinueWith(async t =>
-            {
-                if (t.IsFaulted)
-                {
-                    return $"未能找到{ip}的ISP信息";
-                }
-
-                var result = await t;
-                if (result.IsSuccessStatusCode)
-                {
-                    var taobaoIp = JsonConvert.DeserializeObject<TaobaoIP>(await result.Content.ReadAsStringAsync());
-                    if (taobaoIp.Code == 0)
-                    {
-                        return taobaoIp.IpData.Isp;
-                    }
-                }
-
-                return $"未能找到{ip}的ISP信息";
-            });
-            return task.Result.Result;
-
+            var task = HttpClient.GetAsync($"http://ip.taobao.com/service/getIpInfo.php?ip={ip}", _cts.Token).ContinueWith(t =>
+             {
+                 if (t.IsCompleted)
+                 {
+                     using var content = t.Result.Content;
+                     var taobaoIp = JsonConvert.DeserializeObject<TaobaoIP>(content.ReadAsStringAsync().Result);
+                     if (taobaoIp.Code == 0)
+                     {
+                         return taobaoIp.IpData.Isp;
+                     }
+                 }
+
+                 return $"未能找到{ip}的ISP信息";
+             });
+            return task.Result;
         }
 
-        #endregion
+        #endregion 获取客户端IP地址信息
     }
 }