Browse Source

优化获取IP地理信息的调用

懒得勤快 5 years ago
parent
commit
b05e7f481d
2 changed files with 43 additions and 56 deletions
  1. 27 28
      Masuit.Tools.Abstractions/Models/Email.cs
  2. 16 28
      Masuit.Tools.Core/Net/WebExtension.cs

+ 27 - 28
Masuit.Tools.Abstractions/Models/Email.cs

@@ -9,7 +9,7 @@ namespace Masuit.Tools.Models
         /// <summary>
         /// 发件人用户名
         /// </summary>
-        public string Username { get; set; }
+        public EmailAddress Username { get; set; }
         /// <summary>
         /// 发件人邮箱密码
         /// </summary>
@@ -39,31 +39,30 @@ namespace Masuit.Tools.Models
         /// 是否启用SSL,默认已启用
         /// </summary>
         public bool EnableSsl { get; set; } = true;
+
         /// <summary>
         /// 邮件消息对象
         /// </summary>
-        MailMessage GetClient
+        private MailMessage GetClient()
         {
-            get
+            if (string.IsNullOrEmpty(Tos)) return null;
+            var mailMessage = new MailMessage();
+            //多个接收者                
+            foreach (var str in Tos.Split(','))
             {
-                if (string.IsNullOrEmpty(Tos)) return null;
-                MailMessage mailMessage = new MailMessage();
-                //多个接收者                
-                foreach (string _str in Tos.Split(','))
-                {
-                    mailMessage.To.Add(_str);
-                }
-                mailMessage.From = new MailAddress(Username, Username);
-                mailMessage.Subject = Subject;
-                mailMessage.Body = Body;
-                mailMessage.IsBodyHtml = true;
-                mailMessage.BodyEncoding = System.Text.Encoding.UTF8;
-                mailMessage.SubjectEncoding = System.Text.Encoding.UTF8;
-                mailMessage.Priority = MailPriority.High;
-                return mailMessage;
+                mailMessage.To.Add(str);
             }
+            mailMessage.From = new MailAddress(Username, Username);
+            mailMessage.Subject = Subject;
+            mailMessage.Body = Body;
+            mailMessage.IsBodyHtml = true;
+            mailMessage.BodyEncoding = System.Text.Encoding.UTF8;
+            mailMessage.SubjectEncoding = System.Text.Encoding.UTF8;
+            mailMessage.Priority = MailPriority.High;
+            return mailMessage;
         }
-        SmtpClient GetSmtpClient => new SmtpClient
+
+        private SmtpClient SmtpClient => new SmtpClient
         {
             UseDefaultCredentials = false,
             EnableSsl = EnableSsl,
@@ -74,7 +73,7 @@ namespace Masuit.Tools.Models
         };
 
         //回调方法
-        Action<string> actionSendCompletedCallback = null;
+        Action<string> _actionSendCompletedCallback;
 
         /// <summary>
         /// 使用异步发送邮件
@@ -83,14 +82,14 @@ namespace Masuit.Tools.Models
         /// <returns></returns>
         public void SendAsync(Action<string> completedCallback)
         {
-            using var smtpClient = GetSmtpClient;
-            using var mailMessage = GetClient;
+            using var smtpClient = SmtpClient;
+            using var mailMessage = GetClient();
             if (smtpClient == null || mailMessage == null) return;
             Subject = Subject;
             Body = Body;
             //EnableSsl = false;
             //发送邮件回调方法
-            actionSendCompletedCallback = completedCallback;
+            _actionSendCompletedCallback = completedCallback;
             smtpClient.SendCompleted += SendCompletedCallback;
             smtpClient.SendAsync(mailMessage, "true"); //异步发送邮件,如果回调方法中参数不为"true"则表示发送失败
         }
@@ -100,8 +99,8 @@ namespace Masuit.Tools.Models
         /// </summary>
         public void Send()
         {
-            using SmtpClient smtpClient = GetSmtpClient;
-            using MailMessage mailMessage = GetClient;
+            using var smtpClient = SmtpClient;
+            using var mailMessage = GetClient();
             if (smtpClient == null || mailMessage == null) return;
             Subject = Subject;
             Body = Body;
@@ -119,7 +118,7 @@ namespace Masuit.Tools.Models
             //同一组件下不需要回调方法,直接在此写入日志即可
             //写入日志
             //return;
-            if (actionSendCompletedCallback == null) return;
+            if (_actionSendCompletedCallback == null) return;
             string message;
             if (e.Cancelled)
             {
@@ -127,7 +126,7 @@ namespace Masuit.Tools.Models
             }
             else if (e.Error != null)
             {
-                message = ($"UserState:{(string)e.UserState},Message:{e.Error}");
+                message = $"UserState:{(string)e.UserState},Message:{e.Error}";
             }
             else
             {
@@ -135,7 +134,7 @@ namespace Masuit.Tools.Models
             }
 
             //执行回调方法
-            actionSendCompletedCallback(message);
+            _actionSendCompletedCallback(message);
         }
     }
 #pragma warning restore 1591

+ 16 - 28
Masuit.Tools.Core/Net/WebExtension.cs

@@ -24,23 +24,19 @@ namespace Masuit.Tools.Core.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"}米";
-                    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地址不正确", 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();
+
         /// <summary>
         /// 根据IP地址获取详细地理信息对象
         /// </summary>
@@ -53,15 +49,9 @@ namespace Masuit.Tools.Core.Net
                 return null;
             }
 
-            string ak = ConfigHelper.GetConfigOrDefault("BaiduAK");
-            if (string.IsNullOrEmpty(ak))
-            {
-                throw new Exception("未配置BaiduAK,请先在您的应用程序appsettings.json中下添加BaiduAK配置节(注意大小写);或手动在程序入口处调用IConfiguration的AddToMasuitTools方法");
-            }
-
-            using var client = new HttpClient() { 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 =>
+            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 =>
             {
                 if (t.IsFaulted || t.IsCanceled)
                 {
@@ -77,7 +67,7 @@ namespace Masuit.Tools.Core.Net
                 if (ipAddress.Status == 0)
                 {
                     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 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)
                     {
@@ -86,20 +76,19 @@ namespace Masuit.Tools.Core.Net
                 }
                 else
                 {
-                    using var client2 = new HttpClient { BaseAddress = new Uri("http://ip.taobao.com") };
-                    return await await client2.GetAsync($"/service/getIpInfo.php?ip={ip}").ContinueWith(async tt =>
+                    return await HttpClient.GetAsync($"http://ip.taobao.com/service/getIpInfo.php?ip={ip}").ContinueWith(tt =>
                     {
                         if (tt.IsFaulted || tt.IsCanceled)
                         {
                             return null;
                         }
-                        var result = await tt;
+                        var result = tt.Result;
                         if (!result.IsSuccessStatusCode)
                         {
                             return null;
                         }
 
-                        var taobaoIp = JsonConvert.DeserializeObject<TaobaoIP>(await result.Content.ReadAsStringAsync());
+                        var taobaoIp = JsonConvert.DeserializeObject<TaobaoIP>(result.Content.ReadAsStringAsync().Result);
                         if (taobaoIp.Code == 0)
                         {
                             return new PhysicsAddress()
@@ -136,8 +125,7 @@ namespace Masuit.Tools.Core.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 =>
+            var task = HttpClient.GetAsync($"http://ip.taobao.com/service/getIpInfo.php?ip={ip}").ContinueWith(async t =>
             {
                 if (t.IsFaulted)
                 {