Browse Source

检测客户端的真实IP

懒得勤快 5 năm trước cách đây
mục cha
commit
02a6333b07

+ 5 - 0
src/Masuit.MyBlogs.Core/Controllers/BaseController.cs

@@ -43,6 +43,11 @@ namespace Masuit.MyBlogs.Core.Controllers
 
         public UserInfoOutputDto CurrentUser => HttpContext.Session.Get<UserInfoOutputDto>(SessionKey.UserInfo) ?? new UserInfoOutputDto();
 
+        /// <summary>
+        /// 客户端的真实IP
+        /// </summary>
+        public string ClientIP => string.IsNullOrEmpty(Request.Headers["X-Forwarded-For"]) ? HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString() : Request.Headers["X-Forwarded-For"].ToString();
+
         public IMapper Mapper { get; set; }
         public MapperConfiguration MapperConfig { get; set; }
 

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

@@ -83,7 +83,7 @@ namespace Masuit.MyBlogs.Core.Controllers
             }
             comment.Content = dto.Content.HtmlSantinizerStandard().ClearImgAttributes();
             comment.Browser = dto.Browser ?? Request.Headers[HeaderNames.UserAgent];
-            comment.IP = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
+            comment.IP = ClientIP;
             comment.Location = comment.IP.GetIPLocation().Split("|").Where(s => !int.TryParse(s, out _)).ToHashSet().Join("|");
             comment = CommentService.AddEntitySaved(comment);
             if (comment == null)

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

@@ -138,7 +138,7 @@ namespace Masuit.MyBlogs.Core.Controllers
 
             msg.Content = dto.Content.HtmlSantinizerStandard().ClearImgAttributes();
             msg.Browser = dto.Browser ?? Request.Headers[HeaderNames.UserAgent];
-            msg.IP = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
+            msg.IP = ClientIP;
             msg.Location = msg.IP.GetIPLocation().Split("|").Where(s => !int.TryParse(s, out _)).ToHashSet().Join("|");
             msg = LeaveMessageService.AddEntitySaved(msg);
             if (msg == null)

+ 7 - 2
src/Masuit.MyBlogs.Core/Controllers/PassportController.cs

@@ -28,6 +28,11 @@ namespace Masuit.MyBlogs.Core.Controllers
         /// </summary>
         public IUserInfoService UserInfoService { get; set; }
 
+        /// <summary>
+        /// 客户端的真实IP
+        /// </summary>
+        public string ClientIP => string.IsNullOrEmpty(Request.Headers["X-Forwarded-For"]) ? HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString() : Request.Headers["X-Forwarded-For"].ToString();
+
         /// <summary>
         /// 
         /// </summary>
@@ -75,7 +80,7 @@ namespace Masuit.MyBlogs.Core.Controllers
                     Response.Cookies.Append("username", name, new CookieOptions() { Expires = DateTime.Now.AddDays(7) });
                     Response.Cookies.Append("password", Request.Cookies["password"], new CookieOptions() { Expires = DateTime.Now.AddDays(7) });
                     HttpContext.Session.Set(SessionKey.UserInfo, userInfo);
-                    HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(HangfireBackJob.LoginRecord), "default", userInfo, HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString(), LoginType.Default);
+                    HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(HangfireBackJob.LoginRecord), "default", userInfo, ClientIP, LoginType.Default);
                     if (string.IsNullOrEmpty(from))
                     {
                         return RedirectToAction("Index", "Home");
@@ -116,7 +121,7 @@ namespace Masuit.MyBlogs.Core.Controllers
                     Response.Cookies.Append("username", HttpUtility.UrlEncode(username.Trim()), new CookieOptions() { Expires = DateTime.Now.AddDays(7) });
                     Response.Cookies.Append("password", password.Trim().DesEncrypt(AppConfig.BaiduAK), new CookieOptions() { Expires = DateTime.Now.AddDays(7) });
                 }
-                HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(HangfireBackJob.LoginRecord), "default", userInfo, HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString(), LoginType.Default);
+                HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(HangfireBackJob.LoginRecord), "default", userInfo, ClientIP, LoginType.Default);
                 string refer = Request.Cookies["refer"];
                 return ResultData(null, true, string.IsNullOrEmpty(refer) ? "/" : refer);
             }

+ 3 - 3
src/Masuit.MyBlogs.Core/Controllers/PostController.cs

@@ -234,7 +234,7 @@ namespace Masuit.MyBlogs.Core.Controllers
             post.Content = await ImagebedClient.ReplaceImgSrc(post.Content.HtmlSantinizerStandard().ClearImgAttributes());
             ViewBag.CategoryId = new SelectList(CategoryService.GetQueryNoTracking(c => c.Status == Status.Available), "Id", "Name", post.CategoryId);
             Post p = post.Mapper<Post>();
-            p.IP = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
+            p.IP = ClientIP;
             p.Modifier = p.Author;
             p.ModifierEmail = p.Email;
             p = PostService.AddEntitySaved(p);
@@ -689,7 +689,7 @@ namespace Masuit.MyBlogs.Core.Controllers
                 p.ModifierEmail = user.Email;
             }
 
-            p.IP = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
+            p.IP = ClientIP;
             Mapper.Map(post, p);
             if (!string.IsNullOrEmpty(post.Seminars))
             {
@@ -785,7 +785,7 @@ namespace Masuit.MyBlogs.Core.Controllers
             Post p = post.Mapper<Post>();
             p.Modifier = p.Author;
             p.ModifierEmail = p.Email;
-            p.IP = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
+            p.IP = ClientIP;
             if (!string.IsNullOrEmpty(post.Seminars))
             {
                 var tmp = post.Seminars.Split(',').Distinct();

+ 2 - 2
src/Masuit.MyBlogs.Core/Controllers/SearchController.cs

@@ -41,7 +41,7 @@ namespace Masuit.MyBlogs.Core.Controllers
             ViewBag.Total = 0;
             ViewBag.PageSize = size;
             ViewBag.Keyword = wd;
-            string ip = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
+            string ip = ClientIP;
             string key = "Search:" + ip;
             if (CacheManager.Exists(key) && CacheManager.Get(key) != wd)
             {
@@ -60,7 +60,7 @@ namespace Masuit.MyBlogs.Core.Controllers
                     {
                         KeyWords = wd,
                         SearchTime = DateTime.Now,
-                        IP = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString()
+                        IP = ClientIP
                     });
                     SearchDetailsService.SaveChanges();
                     HttpContext.Session.Set("search:" + wd, wd.ToByteArray());

+ 3 - 3
src/Masuit.MyBlogs.Core/Controllers/ToolsController.cs

@@ -28,7 +28,7 @@ namespace Masuit.MyBlogs.Core.Controllers
         {
             if (string.IsNullOrEmpty(ip))
             {
-                ip = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
+                ip = ClientIP;
             }
             ViewBag.IP = ip;
             PhysicsAddress address = await ip.GetPhysicsAddressInfo();
@@ -50,7 +50,7 @@ namespace Masuit.MyBlogs.Core.Controllers
         {
             if (string.IsNullOrEmpty(lat) || string.IsNullOrEmpty(lng))
             {
-                var ip = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
+                var ip = ClientIP;
 #if DEBUG
                 var r = new Random();
                 ip = $"{r.Next(210)}.{r.Next(255)}.{r.Next(255)}.{r.Next(255)}";
@@ -75,7 +75,7 @@ namespace Masuit.MyBlogs.Core.Controllers
         {
             if (string.IsNullOrEmpty(addr))
             {
-                var ip = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
+                var ip = ClientIP;
 #if DEBUG
                 Random r = new Random();
                 ip = $"{r.Next(210)}.{r.Next(255)}.{r.Next(255)}.{r.Next(255)}";

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

@@ -26,7 +26,7 @@ namespace Masuit.MyBlogs.Core.Extensions
         public override void OnActionExecuting(ActionExecutingContext context)
         {
             var request = context.HttpContext.Request;
-            var ip = context.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
+            var ip = string.IsNullOrEmpty(context.HttpContext.Request.Headers["X-Forwarded-For"]) ? context.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString() : context.HttpContext.Request.Headers["X-Forwarded-For"].ToString();
             var sessionToken = context.HttpContext.Session.Get<string>("FullAccessViewToken");
             if (ip.IsDenyIpAddress() && string.IsNullOrEmpty(sessionToken))
             {

+ 10 - 0
src/Masuit.MyBlogs.Core/Masuit.MyBlogs.Core.xml

@@ -345,6 +345,11 @@
             LinksService
             </summary>
         </member>
+        <member name="P:Masuit.MyBlogs.Core.Controllers.BaseController.ClientIP">
+            <summary>
+            客户端的真实IP
+            </summary>
+        </member>
         <member name="M:Masuit.MyBlogs.Core.Controllers.BaseController.ResultData(System.Object,System.Boolean,System.String,System.Boolean,System.Net.HttpStatusCode)">
             <summary>
             响应数据
@@ -1188,6 +1193,11 @@
             用户
             </summary>
         </member>
+        <member name="P:Masuit.MyBlogs.Core.Controllers.PassportController.ClientIP">
+            <summary>
+            客户端的真实IP
+            </summary>
+        </member>
         <member name="M:Masuit.MyBlogs.Core.Controllers.PassportController.ResultData(System.Object,System.Boolean,System.String)">
             <summary>