1
0
Эх сурвалжийг харах

优化获取客户端ip地址

懒得勤快 4 жил өмнө
parent
commit
c801d4e4fc

+ 8 - 11
src/Masuit.MyBlogs.Core/Common/CommonHelper.cs

@@ -31,7 +31,7 @@ namespace Masuit.MyBlogs.Core.Common
     {
         static CommonHelper()
         {
-            ThreadPool.QueueUserWorkItem(s =>
+            ThreadPool.QueueUserWorkItem(_ =>
             {
                 while (true)
                 {
@@ -82,12 +82,12 @@ namespace Masuit.MyBlogs.Core.Common
         /// <summary>
         /// 每IP错误的次数统计
         /// </summary>
-        public static ConcurrentDictionary<string, int> IPErrorTimes { get; set; } = new ConcurrentDictionary<string, int>();
+        public static ConcurrentDictionary<string, int> IPErrorTimes { get; set; } = new();
 
         /// <summary>
         /// 系统设定
         /// </summary>
-        public static ConcurrentDictionary<string, string> SystemSettings { get; set; } = new ConcurrentDictionary<string, string>();
+        public static ConcurrentDictionary<string, string> SystemSettings { get; set; } = new();
 
         /// <summary>
         /// 网站启动时间
@@ -135,9 +135,9 @@ namespace Masuit.MyBlogs.Core.Common
             return false;
         }
 
-        private static readonly DbSearcher IPSearcher = new DbSearcher(Path.Combine(AppContext.BaseDirectory + "App_Data", "ip2region.db"));
-        public static readonly DatabaseReader MaxmindReader = new DatabaseReader(Path.Combine(AppContext.BaseDirectory + "App_Data", "GeoLite2-City.mmdb"));
-        private static readonly DatabaseReader MaxmindAsnReader = new DatabaseReader(Path.Combine(AppContext.BaseDirectory + "App_Data", "GeoLite2-ASN.mmdb"));
+        private static readonly DbSearcher IPSearcher = new(Path.Combine(AppContext.BaseDirectory + "App_Data", "ip2region.db"));
+        public static readonly DatabaseReader MaxmindReader = new(Path.Combine(AppContext.BaseDirectory + "App_Data", "GeoLite2-City.mmdb"));
+        private static readonly DatabaseReader MaxmindAsnReader = new(Path.Combine(AppContext.BaseDirectory + "App_Data", "GeoLite2-ASN.mmdb"));
 
         public static AsnResponse GetIPAsn(this string ip)
         {
@@ -156,11 +156,8 @@ namespace Masuit.MyBlogs.Core.Common
 
         public static string GetIPLocation(this string ips)
         {
-            return ips.Split(',', StringSplitOptions.RemoveEmptyEntries).Select(s =>
-            {
-                var (location, network) = GetIPLocation(IPAddress.Parse(s.Trim()));
-                return location + "|" + network;
-            }).Join(" , ");
+            var (location, network) = GetIPLocation(IPAddress.Parse(ips));
+            return location + "|" + network;
         }
 
         public static (string location, string network) GetIPLocation(this IPAddress ip)

+ 5 - 30
src/Masuit.MyBlogs.Core/Common/HttpContextExtension.cs

@@ -1,6 +1,4 @@
-using Masuit.MyBlogs.Core.Configs;
-using Masuit.Tools;
-using MaxMind.GeoIP2.Responses;
+using Masuit.Tools;
 using Microsoft.AspNetCore.Http;
 using Microsoft.Net.Http.Headers;
 
@@ -15,34 +13,11 @@ namespace Masuit.MyBlogs.Core.Common
         /// <returns></returns>
         public static string Location(this HttpRequest request)
         {
-            return (string)request.HttpContext.Items.GetOrAdd("ip.location", () => request.HttpContext.GetTrueIP().GetIPLocation());
-        }
-
-        /// <summary>
-        /// asn信息
-        /// </summary>
-        /// <param name="request"></param>
-        /// <returns></returns>
-        public static AsnResponse Asn(this HttpRequest request)
-        {
-            return (AsnResponse)request.HttpContext.Items.GetOrAdd("ip.asn", () => request.HttpContext.GetTrueIP().GetIPAsn());
-        }
-
-        /// <summary>
-        /// 获取真实客户端ip
-        /// </summary>
-        /// <param name="context"></param>
-        /// <returns></returns>
-        public static string GetTrueIP(this HttpContext context)
-        {
-            var ip = context.Connection.RemoteIpAddress.ToString();
-            var trueip = context.Request.Headers[AppConfig.TrueClientIPHeader].ToString();
-            if (!string.IsNullOrEmpty(trueip) && ip != trueip)
+            return (string)request.HttpContext.Items.GetOrAdd("ip.location", () =>
             {
-                ip = trueip;
-            }
-
-            return ip;
+                var (location, network) = request.HttpContext.Connection.RemoteIpAddress.GetIPLocation();
+                return location + "|" + network;
+            });
         }
 
         /// <summary>

+ 3 - 3
src/Masuit.MyBlogs.Core/Common/TrackData.cs

@@ -14,7 +14,7 @@ namespace Masuit.MyBlogs.Core.Common
         /// <summary>
         /// 请求日志
         /// </summary>
-        public static ConcurrentDictionary<string, RequestLog> RequestLogs { get; } = new ConcurrentDictionary<string, RequestLog>();
+        public static ConcurrentDictionary<string, RequestLog> RequestLogs { get; } = new();
 
         /// <summary>
         /// 刷写日志
@@ -50,8 +50,8 @@ namespace Masuit.MyBlogs.Core.Common
 
     public class RequestLog
     {
-        public HashSet<string> UserAgents { get; } = new HashSet<string>();
-        public HashSet<string> RequestUrls { get; } = new HashSet<string>();
+        public HashSet<string> UserAgents { get; } = new();
+        public HashSet<string> RequestUrls { get; } = new();
         public int Count { get; set; }
     }
 }

+ 1 - 1
src/Masuit.MyBlogs.Core/Controllers/BaseController.cs

@@ -50,7 +50,7 @@ namespace Masuit.MyBlogs.Core.Controllers
         /// <summary>
         /// 客户端的真实IP
         /// </summary>
-        public string ClientIP => HttpContext.GetTrueIP();
+        public string ClientIP => HttpContext.Connection.RemoteIpAddress.ToString();
 
         /// <summary>
         /// 普通访客是否token合法

+ 4 - 11
src/Masuit.MyBlogs.Core/Controllers/ErrorController.cs

@@ -2,6 +2,7 @@
 using Masuit.MyBlogs.Core.Common;
 using Masuit.MyBlogs.Core.Configs;
 using Masuit.MyBlogs.Core.Extensions;
+using Masuit.MyBlogs.Core.Extensions.Firewall;
 using Masuit.MyBlogs.Core.Infrastructure.Services.Interface;
 using Masuit.Tools;
 using Masuit.Tools.Logging;
@@ -15,9 +16,7 @@ using Microsoft.EntityFrameworkCore;
 using Microsoft.Net.Http.Headers;
 using System;
 using System.Linq;
-using System.Net;
 using System.Web;
-using Masuit.MyBlogs.Core.Extensions.Firewall;
 using SameSiteMode = Microsoft.AspNetCore.Http.SameSiteMode;
 
 namespace Masuit.MyBlogs.Core.Controllers
@@ -58,13 +57,7 @@ namespace Masuit.MyBlogs.Core.Controllers
             {
                 string err;
                 var req = HttpContext.Request;
-                var ip = HttpContext.Connection.RemoteIpAddress.ToString();
-                var trueip = Request.Headers[AppConfig.TrueClientIPHeader].ToString();
-                if (!string.IsNullOrEmpty(trueip) && ip != trueip)
-                {
-                    ip = trueip;
-                }
-
+                var ip = HttpContext.Connection.RemoteIpAddress;
                 switch (feature.Error)
                 {
                     case DbUpdateConcurrencyException ex:
@@ -92,9 +85,9 @@ namespace Masuit.MyBlogs.Core.Controllers
                             ex.Message
                         });
                     case AccessDenyException _:
-                        var (location, network) = IPAddress.Parse(ip).GetIPLocation();
+                        var (location, network) = ip.GetIPLocation();
                         var tips = Template.Create(CommonHelper.SystemSettings.GetOrAdd("AccessDenyTips", @"<h4>遇到了什么问题?</h4>
-                <h4>基于主观因素考虑,您所在的地区暂时不允许访问本站,如有疑问,请联系站长!或者请联系站长开通本站的访问权限!</h4>")).Set("clientip", ip).Set(nameof(location), location).Set(nameof(network), network).Render();
+                <h4>基于主观因素考虑,您所在的地区暂时不允许访问本站,如有疑问,请联系站长!或者请联系站长开通本站的访问权限!</h4>")).Set("clientip", ip.ToString()).Set(nameof(location), location).Set(nameof(network), network).Render();
                         Response.StatusCode = 403;
                         return View("AccessDeny", tips);
                     case TempDenyException _:

+ 1 - 1
src/Masuit.MyBlogs.Core/Extensions/Firewall/FirewallAttribute.cs

@@ -30,7 +30,7 @@ namespace Masuit.MyBlogs.Core.Extensions.Firewall
         public override void OnActionExecuting(ActionExecutingContext context)
         {
             var request = context.HttpContext.Request;
-            var ip = context.HttpContext.GetTrueIP();
+            var ip = context.HttpContext.Connection.RemoteIpAddress.ToString();
             var tokenValid = request.Cookies["Email"].MDString3(AppConfig.BaiduAK).Equals(request.Cookies["FullAccessToken"]);
             if (ip.IsDenyIpAddress() && !tokenValid)
             {

+ 2 - 4
src/Masuit.MyBlogs.Core/Extensions/Firewall/RequestInterceptMiddleware.cs

@@ -43,9 +43,7 @@ namespace Masuit.MyBlogs.Core.Extensions.Firewall
                 context.Response.StatusCode = 404;
                 return;
             }
-            var ip = context.GetTrueIP();
-            context.Items.AddOrUpdate("ip.asn", ip.GetIPAsn());
-            context.Items.AddOrUpdate("ip.location", ip.GetIPLocation());
+            var ip = context.Connection.RemoteIpAddress.ToString();
             var path = HttpUtility.UrlDecode(request.Path + request.QueryString, Encoding.UTF8);
             var requestUrl = HttpUtility.UrlDecode(request.Scheme + "://" + request.Host + path);
             var match = Regex.Match(path ?? "", CommonHelper.BanRegex);
@@ -99,7 +97,7 @@ namespace Masuit.MyBlogs.Core.Extensions.Firewall
                     Count = 1,
                     RequestUrls = { requestUrl },
                     UserAgents = { request.Headers[HeaderNames.UserAgent] }
-                }, (s, i) =>
+                }, (_, i) =>
                 {
                     i.UserAgents.Add(request.Headers[HeaderNames.UserAgent]);
                     i.RequestUrls.Add(requestUrl);

+ 0 - 17
src/Masuit.MyBlogs.Core/Extensions/IApplicationBuilderExtensions.cs

@@ -1,17 +0,0 @@
-using Masuit.MyBlogs.Core.Extensions.Firewall;
-using Microsoft.AspNetCore.Builder;
-
-namespace Masuit.MyBlogs.Core.Extensions
-{
-    public static class IApplicationBuilderExtensions
-    {
-        public static IApplicationBuilder UseRequestIntercept(this IApplicationBuilder builder)
-        {
-            return builder.UseMiddleware<RequestInterceptMiddleware>();
-        }
-        public static IApplicationBuilder UseActivity(this IApplicationBuilder builder)
-        {
-            return builder.UseMiddleware<ActivityMiddleware>();
-        }
-    }
-}

+ 1 - 0
src/Masuit.MyBlogs.Core/PrepareStartup.cs

@@ -131,6 +131,7 @@ namespace Masuit.MyBlogs.Core
             {
                 options.ForwardLimit = null;
                 options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
+                options.ForwardedForHeaderName = AppConfig.TrueClientIPHeader;
                 options.KnownNetworks.Clear();
                 options.KnownProxies.Clear();
             });

+ 1 - 1
src/Masuit.MyBlogs.Core/Startup.cs

@@ -143,7 +143,7 @@ namespace Masuit.MyBlogs.Core
             app.SetupHttpsRedirection(Configuration);
             app.UseDefaultFiles().UseStaticFiles();
             app.UseSession().UseCookiePolicy().UseMiniProfiler(); //注入Session
-            app.UseRequestIntercept(); //启用网站请求拦截
+            app.UseMiddleware<RequestInterceptMiddleware>(); //启用网站请求拦截
             app.SetupHangfire();
             app.UseResponseCaching().UseResponseCompression(); //启动Response缓存
             app.UseWhen(c => !c.Request.Path.StartsWithSegments("/_") && c.Request.Scheme.StartsWith("http"), builder => builder.UseMiddleware<TranslateMiddleware>());

+ 1 - 3
src/Masuit.MyBlogs.Core/Views/Error/Index.cshtml

@@ -73,12 +73,10 @@
                 vertical-align: middle;
             }
     </style>
-    <meta property="qc:admins" content="153016004160513163145" />
     <meta charset="utf-8">
     <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
     <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
     <link href="https://cdn.staticfile.org/normalize/8.0.1/normalize.min.css" rel="stylesheet">
-    <link href="https://cdn.staticfile.org/animate.css/3.7.0/animate.min.css" rel="stylesheet">
     <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" />
     <script src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js"></script>
     <script src="https://cdn.staticfile.org/jquery.ripples/0.5.3/jquery.ripples.min.js"></script>
@@ -144,7 +142,7 @@
             catch (e) {
                 $('.error').show().text(e);
             }
-        }, 100);
+        }, 1000);
     });
 </script>
 <script src="~/Scripts/notify.min.js"></script>

+ 1 - 3
src/Masuit.MyBlogs.Core/Views/Error/ServiceUnavailable.cshtml

@@ -67,12 +67,10 @@
                 vertical-align: middle;
             }
     </style>
-    <meta property="qc:admins" content="153016004160513163145" />
     <meta charset="utf-8">
     <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
     <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
     <link href="https://cdn.staticfile.org/normalize/8.0.1/normalize.min.css" rel="stylesheet">
-    <link href="https://cdn.staticfile.org/animate.css/3.7.0/animate.min.css" rel="stylesheet">
     <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" />
     <script src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js"></script>
     <script src="https://cdn.staticfile.org/jquery.ripples/0.5.3/jquery.ripples.min.js"></script>
@@ -147,7 +145,7 @@
             catch (e) {
                 $('.error').show().text(e);
             }
-        }, 100);
+        }, 1000);
     });
 </script>
 <script src="~/Scripts/notify.min.js"></script>

+ 1 - 1
src/Masuit.MyBlogs.Core/Views/Tools/GetIPInfo.cshtml

@@ -38,7 +38,7 @@
         <table class="table table-bordered table-condensed table-hover">
             <tr>
                 <td>IP路由信息:</td>
-                <td>@Model.asn.Network?.ToString()</td>
+                <td>@Model.asn.Network</td>
             </tr>
             <tr>
                 <td>IP机房信息:</td>

BIN
src/Masuit.MyBlogs.Core/wwwroot/Assets/images/404/40410.jpg


BIN
src/Masuit.MyBlogs.Core/wwwroot/Assets/images/503/5031.jpg


BIN
src/Masuit.MyBlogs.Core/wwwroot/Assets/images/503/5032.jpg


BIN
src/Masuit.MyBlogs.Core/wwwroot/Assets/images/503/5033.jpg


BIN
src/Masuit.MyBlogs.Core/wwwroot/Assets/images/503/5034.jpg


BIN
src/Masuit.MyBlogs.Core/wwwroot/Assets/images/503/5035.jpg


BIN
src/Masuit.MyBlogs.Core/wwwroot/Assets/images/503/5036.jpg


BIN
src/Masuit.MyBlogs.Core/wwwroot/Assets/images/503/5037.jpg