Browse Source

1.www重定向到非www
2.bug修正

懒得勤快 6 years ago
parent
commit
13a2c0fb5d

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

@@ -116,7 +116,7 @@ namespace Masuit.MyBlogs.Core.Controllers
                         {
                             Expires = DateTime.Now.AddDays(7)
                         });
-                        Response.Cookies.Append("password", Request.Cookies["password"], new CookieOptions()
+                        Response.Cookies.Append("password", Request.Cookies["password"].DesEncrypt(AppConfig.BaiduAK), new CookieOptions()
                         {
                             Expires = DateTime.Now.AddDays(7)
                         });

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

@@ -131,7 +131,7 @@ namespace Masuit.MyBlogs.Core.Controllers
         public ActionResult Submit(Issue issue)
         {
             issue.Description = CommonHelper.ReplaceImgSrc(Regex.Replace(issue.Description, @"<img\s+[^>]*\s*src\s*=\s*['""]?(\S+\.\w{3,4})['""]?[^/>]*/>", "<img src=\"$1\"/>")).Replace("/thumb150/", "/large/");
-            issue.IPAddress = HttpContext.Connection.RemoteIpAddress.ToString();
+            issue.IPAddress = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
             Issue bug = IssueService.AddEntitySaved(issue);
             if (bug != null)
             {

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

@@ -80,7 +80,7 @@ namespace Masuit.MyBlogs.Core.Controllers
             comment.Content = Regex.Replace(comment.Content.HtmlSantinizerStandard().ConvertImgSrcToRelativePath(), @"<img\s+[^>]*\s*src\s*=\s*['""]?(\S+\.\w{3,4})['""]?[^/>]*/>", "<img src=\"$1\"/>");
             comment.CommentDate = DateTime.Now;
             comment.Browser = comment.Browser ?? Request.Headers[HeaderNames.UserAgent];
-            comment.IP = HttpContext.Connection.RemoteIpAddress.ToString();
+            comment.IP = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
             Comment com = CommentService.AddEntitySaved(comment.Mapper<Comment>());
             if (com != null)
             {

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

@@ -281,7 +281,7 @@ namespace Masuit.MyBlogs.Core.Controllers
             }
             if (page == 1)
             {
-                //posts = postList.Where(p => p.IsFixedTop).OrderByDescending(p => p.ModifyDate).AsEnumerable().Union(posts).ToList();
+                posts = postList.Where(p => p.IsFixedTop).OrderByDescending(p => p.ModifyDate).AsEnumerable().Union(posts).ToList();
             }
             return new IndexPageViewModel()
             {

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

@@ -150,7 +150,7 @@ namespace Masuit.MyBlogs.Core.Controllers
             msg.PostDate = DateTime.Now;
             msg.Content = Regex.Replace(msg.Content.HtmlSantinizerStandard().ConvertImgSrcToRelativePath(), @"<img\s+[^>]*\s*src\s*=\s*['""]?(\S+\.\w{3,4})['""]?[^/>]*/>", "<img src=\"$1\"/>");
             msg.Browser = msg.Browser ?? Request.Headers[HeaderNames.UserAgent];
-            msg.IP = HttpContext.Connection.RemoteIpAddress.ToString();
+            msg.IP = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
             LeaveMessage msg2 = LeaveMessageService.AddEntitySaved(msg.Mapper<LeaveMessage>());
             if (msg2 != null)
             {

+ 4 - 3
src/Masuit.MyBlogs.Core/Controllers/PassportController.cs

@@ -14,6 +14,7 @@ using Microsoft.AspNetCore.Http;
 using Microsoft.AspNetCore.Mvc;
 using System;
 using System.Web;
+using Common;
 
 namespace Masuit.MyBlogs.Core.Controllers
 {
@@ -88,9 +89,9 @@ namespace Masuit.MyBlogs.Core.Controllers
                 if (userInfo != null)
                 {
                     Response.Cookies.Append("username", name, new CookieOptions() { Expires = DateTime.Now.AddDays(7) });
-                    Response.Cookies.Append("password", pwd, new CookieOptions() { Expires = DateTime.Now.AddDays(7) });
+                    Response.Cookies.Append("password", pwd.DesEncrypt(AppConfig.BaiduAK), new CookieOptions() { Expires = DateTime.Now.AddDays(7) });
                     HttpContext.Session.SetByRedis(SessionKey.UserInfo, userInfo);
-                    HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(HangfireBackJob.LoginRecord), "default", userInfo, HttpContext.Connection.RemoteIpAddress.ToString(), LoginType.Default);
+                    HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(HangfireBackJob.LoginRecord), "default", userInfo, HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString(), LoginType.Default);
                     if (string.IsNullOrEmpty(from))
                     {
                         return RedirectToAction("Index", "Home");
@@ -131,7 +132,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.ToString(), LoginType.Default);
+                HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(HangfireBackJob.LoginRecord), "default", userInfo, HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString(), LoginType.Default);
                 string refer = Request.Cookies["refer"];
                 return ResultData(null, true, string.IsNullOrEmpty(refer) ? "/" : refer);
             }

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

@@ -80,7 +80,7 @@ namespace Masuit.MyBlogs.Core.Controllers
         {
             if (string.IsNullOrEmpty(lat) || string.IsNullOrEmpty(lng))
             {
-                var ip = HttpContext.Connection.RemoteIpAddress.ToString();
+                var ip = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
 #if DEBUG
                 Random r = new Random();
                 ip = $"{r.StrictNext(210)}.{r.StrictNext(255)}.{r.StrictNext(255)}.{r.StrictNext(255)}";
@@ -107,7 +107,7 @@ namespace Masuit.MyBlogs.Core.Controllers
         {
             if (string.IsNullOrEmpty(addr))
             {
-                var ip = HttpContext.Connection.RemoteIpAddress.ToString();
+                var ip = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
 #if DEBUG
                 Random r = new Random();
                 ip = $"{r.StrictNext(210)}.{r.StrictNext(255)}.{r.StrictNext(255)}.{r.StrictNext(255)}";
@@ -144,7 +144,7 @@ namespace Masuit.MyBlogs.Core.Controllers
         {
             if (string.IsNullOrEmpty(ip))
             {
-                ip = HttpContext.Connection.RemoteIpAddress.ToString();
+                ip = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
             }
             PhysicsAddress address = await ip.GetPhysicsAddressInfo();
             return address;

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

@@ -83,7 +83,7 @@ namespace Masuit.MyBlogs.Core.Controllers
                         {
                             KeyWords = wd,
                             SearchTime = DateTime.Now,
-                            IP = HttpContext.Connection.RemoteIpAddress.ToString()
+                            IP = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString()
                         });
                         HttpContext.Session.Set("search:" + wd, wd);
                     }

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

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

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

@@ -38,7 +38,7 @@ namespace Masuit.MyBlogs.Core.Extensions
                     if (userInfo != null)
                     {
                         filterContext.HttpContext.Response.Cookies.Append("username", name, new CookieOptions() { Expires = DateTime.Now.AddDays(7) });
-                        filterContext.HttpContext.Response.Cookies.Append("password", pwd, new CookieOptions() { Expires = DateTime.Now.AddDays(7) });
+                        filterContext.HttpContext.Response.Cookies.Append("password", pwd.DesEncrypt(AppConfig.BaiduAK), new CookieOptions() { Expires = DateTime.Now.AddDays(7) });
                         filterContext.HttpContext.Session.SetByRedis(SessionKey.UserInfo, userInfo);
                     }
                     else

+ 22 - 20
src/Masuit.MyBlogs.Core/Extensions/FirewallMiddleware.cs

@@ -1,4 +1,8 @@
-using Masuit.Tools;
+using Common;
+using Hangfire;
+using Masuit.MyBlogs.Core.Extensions.Hangfire;
+using Masuit.Tools;
+using Masuit.Tools.Logging;
 using Masuit.Tools.NoSQL;
 using Microsoft.AspNetCore.Http;
 using Microsoft.Net.Http.Headers;
@@ -34,30 +38,28 @@ namespace Masuit.MyBlogs.Core.Extensions
                 return;
             }
 
-#if DEBUG
-            if (context.Connection.RemoteIpAddress.ToString().IsDenyIpAddress())
+            try
             {
-                await context.Response.WriteAsync($"检测到您的IP({context.Connection.RemoteIpAddress})异常,已被本站禁止访问,如有疑问,请联系站长!");
-                BackgroundJob.Enqueue(() => HangfireBackJob.InterceptLog(new IpIntercepter()
+                if (context.Connection.RemoteIpAddress.MapToIPv4().ToString().IsDenyIpAddress())
+                {
+                    await context.Response.WriteAsync($"检测到您的IP({context.Connection.RemoteIpAddress.MapToIPv4()})异常,已被本站禁止访问,如有疑问,请联系站长!");
+                    BackgroundJob.Enqueue(() => HangfireBackJob.InterceptLog(new IpIntercepter()
+                    {
+                        IP = context.Connection.RemoteIpAddress.MapToIPv4().ToString(),
+                        RequestUrl = context.Request.Host.ToString(),
+                        Time = DateTime.Now
+                    }));
+                    return;
+                }
+                bool isSpider = context.Request.Headers[HeaderNames.UserAgent].ToString().Contains(new[]
                 {
-                    IP = context.Connection.RemoteIpAddress.ToString(),
-                    RequestUrl = context.Request.Host.ToString(),
-                    Time = DateTime.Now
-                }));
-                return;
-            }
-#endif
-            bool isSpider = context.Request.Headers[HeaderNames.UserAgent].ToString().Contains(new[]
-            {
                 "DNSPod",
                 "Baidu",
                 "spider",
                 "Python",
                 "bot"
             });
-            if (isSpider) return;
-            try
-            {
+                if (isSpider) return;
                 var times = _redisHelper.StringIncrement("Frequency:" + context.Connection.Id);
                 _redisHelper.Expire("Frequency:" + context.Connection.Id, TimeSpan.FromMinutes(1));
                 if (times > 300)
@@ -65,12 +67,12 @@ namespace Masuit.MyBlogs.Core.Extensions
                     await context.Response.WriteAsync($"检测到您的IP({context.Connection.RemoteIpAddress})访问过于频繁,已被本站暂时禁止访问,如有疑问,请联系站长!");
                     return;
                 }
+                await _next.Invoke(context);
             }
-            catch
+            catch (Exception e)
             {
-                // ignored
+                LogManager.Error($"异常源:{e.Source},异常类型:{e.GetType().Name},\n请求路径:{context.Request.Scheme}://{context.Request.Host}{context.Request.Path.Value},客户端用户代理:{context.Request.Headers["User-Agent"]},客户端IP:{context.Connection.RemoteIpAddress}\t", e);
             }
-            await _next.Invoke(context);
         }
     }
 }

+ 3 - 1
src/Masuit.MyBlogs.Core/Extensions/IApplicationBuilderExtensions.cs

@@ -8,13 +8,15 @@ namespace Masuit.MyBlogs.Core.Extensions
         {
             return builder.UseMiddleware<FirewallMiddleware>();
         }
+
         public static IApplicationBuilder UseException(this IApplicationBuilder builder)
         {
             return builder.UseMiddleware<ExceptionMiddleware>();
         }
+
         public static IApplicationBuilder UseRequestIntercept(this IApplicationBuilder builder)
         {
             return builder.UseMiddleware<RequestInterceptMiddleware>();
         }
     }
-}
+}

+ 31 - 0
src/Masuit.MyBlogs.Core/Extensions/NonWwwRule.cs

@@ -0,0 +1,31 @@
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Rewrite;
+using System;
+using System.Text;
+using System.Text.RegularExpressions;
+
+namespace Masuit.MyBlogs.Core.Extensions
+{
+    public class NonWwwRule : IRule
+    {
+        public void ApplyRule(RewriteContext context)
+        {
+            var req = context.HttpContext.Request;
+            var currentHost = req.Host;
+            if (currentHost.Host.Equals("127.0.0.1") || currentHost.Host.Equals("localhost", StringComparison.InvariantCultureIgnoreCase))
+            {
+                context.Result = RuleResult.ContinueRules;
+                return;
+            }
+
+            if (Regex.IsMatch(currentHost.Host, @"(\w+\.)(.+\..+)", RegexOptions.Compiled))
+            {
+                string domain = Regex.Match(currentHost.Host, @"(\w+\.)(.+\..+)").Groups[2].Value;
+                var newHost = new HostString(domain);
+                var newUrl = new StringBuilder().Append("https://").Append(newHost).Append(req.PathBase).Append(req.Path).Append(req.QueryString);
+                context.HttpContext.Response.Redirect(newUrl.ToString());
+                context.Result = RuleResult.EndResponse;
+            }
+        }
+    }
+}

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

@@ -1,6 +1,8 @@
 using Masuit.Tools.Core.Net;
+using Masuit.Tools.Logging;
 using Masuit.Tools.NoSQL;
 using Microsoft.AspNetCore.Http;
+using System;
 using System.Threading.Tasks;
 
 namespace Masuit.MyBlogs.Core.Extensions
@@ -26,12 +28,19 @@ namespace Masuit.MyBlogs.Core.Extensions
 
         public async Task Invoke(HttpContext context)
         {
-            if (!context.Session.TryGetValue(context.Connection.Id, out _))
+            try
             {
-                context.Session.Set(context.Connection.Id, context.Connection.Id);
-                _redisHelper.StringIncrement("Interview:ViewCount");
+                if (!context.Session.TryGetValue(context.Connection.Id, out _))
+                {
+                    context.Session.Set(context.Connection.Id, context.Connection.Id);
+                    _redisHelper.StringIncrement("Interview:ViewCount");
+                }
+                await _next.Invoke(context);
+            }
+            catch (Exception e)
+            {
+                LogManager.Error($"异常源:{e.Source},异常类型:{e.GetType().Name},\n请求路径:{context.Request.Scheme}://{context.Request.Host}{context.Request.Path.Value},客户端用户代理:{context.Request.Headers["User-Agent"]},客户端IP:{context.Connection.RemoteIpAddress}\t", e);
             }
-            await _next.Invoke(context);
         }
     }
 }

+ 13 - 0
src/Masuit.MyBlogs.Core/Extensions/RewriteOptionsExtensions.cs

@@ -0,0 +1,13 @@
+using Microsoft.AspNetCore.Rewrite;
+
+namespace Masuit.MyBlogs.Core.Extensions
+{
+    public static class RewriteOptionsExtensions
+    {
+        public static RewriteOptions AddRedirectToNonWww(this RewriteOptions options)
+        {
+            options.Rules.Add(new NonWwwRule());
+            return options;
+        }
+    }
+}

+ 5 - 7
src/Masuit.MyBlogs.Core/Startup.cs

@@ -176,12 +176,13 @@ namespace Masuit.MyBlogs.Core
                 app.UseExceptionHandler("/Home/Error");
                 app.UseHsts();
                 app.UseException();
-                using (var fs = File.OpenText(Path.Combine(env.ContentRootPath, "App_Data", "rewrite.xml")))
-                {
-                    app.UseRewriter(new RewriteOptions().AddIISUrlRewrite(fs));
-                }
             }
 
+            app.UseRewriter(new RewriteOptions().AddRedirectToNonWww());
+            app.UseStaticHttpContext(); //注入静态HttpContext对象
+
+            app.UseSession(); //注入Session
+
             app.UseHttpsRedirection().UseStaticFiles(new StaticFileOptions //静态资源缓存策略
             {
                 OnPrepareResponse = context =>
@@ -204,9 +205,6 @@ namespace Masuit.MyBlogs.Core
                 Console.WriteLine("索引库创建完成!");
             }
 
-            app.UseStaticHttpContext(); //注入静态HttpContext对象
-            app.UseSession(); //注入Session
-
             app.UseEFSecondLevelCache(); //启动EF二级缓存
             app.UseHangfireServer().UseHangfireDashboard("/taskcenter", new DashboardOptions()
             {

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

@@ -1,7 +1,7 @@
 @{
     ViewBag.Title = "留言板";
     Layout = "~/Views/Shared/_Layout.cshtml";
-    string cid = 0 + Context.Request.Query["cid"];
+    string cid = string.IsNullOrEmpty(Context.Request.Query["cid"]) ? "0" : Context.Request.Query["cid"].ToString();
 }
 <link href="~/Assets/layui/css/layui.min.css" rel="stylesheet" />
 <script src="~/Assets/layui/layui.all.js"></script>

+ 1 - 1
src/Masuit.MyBlogs.Core/Views/Msg/Index_Admin.cshtml

@@ -5,7 +5,7 @@
     ViewBag.Title = "留言板";
     Layout = "~/Views/Shared/_Layout.cshtml";
     UserInfoOutputDto user = Context.Session.GetByRedis<UserInfoOutputDto>(SessionKey.UserInfo);
-    string cid = 0 + Context.Request.Query["cid"];
+    string cid = string.IsNullOrEmpty(Context.Request.Query["cid"]) ? "0" : Context.Request.Query["cid"].ToString();
 }
 <link href="~/Assets/layui/css/layui.min.css" rel="stylesheet" />
 <script src="~/Assets/layui/layui.all.js"></script>

+ 1 - 1
src/Masuit.MyBlogs.Core/Views/Post/Details.cshtml

@@ -10,7 +10,7 @@
     ViewBag.Title = Model.Title;
     Layout = "~/Views/Shared/_Layout.cshtml";
     string[] colors = { "success", "info", "primary", "warning", "danger", "default", "primary" };
-    string cid = 0 + Context.Request.Query["cid"];
+    string cid = string.IsNullOrEmpty(Context.Request.Query["cid"]) ? "0" : Context.Request.Query["cid"].ToString();
 }
 <link href="~/Assets/layui/css/layui.css" rel="stylesheet" />
 <link href="~/Assets/jquery.tocify/jquery.tocify.min.css" rel="stylesheet" />

+ 2 - 2
src/Masuit.MyBlogs.Core/Views/Post/Details_Admin.cshtml

@@ -13,13 +13,13 @@
     Layout = "~/Views/Shared/_Layout.cshtml";
     string[] colors = { "success", "info", "primary", "warning", "danger", "default", "primary" };
     UserInfoOutputDto user = Context.Session.GetByRedis<UserInfoOutputDto>(SessionKey.UserInfo);
-    string cid = 0 + Context.Request.Query["cid"];
+    string cid = string.IsNullOrEmpty(Context.Request.Query["cid"]) ? "0" : Context.Request.Query["cid"].ToString();
 }
 <style>
     #gooey-h {
         position: fixed;
         bottom: 250px;
-        right: 0px;
+        right: 0;
         z-index: 3;
     }
 </style>