Browse Source

防火墙规则升级

懒得勤快 6 years ago
parent
commit
742d23a0da

File diff suppressed because it is too large
+ 0 - 0
src/Masuit.MyBlogs.Core/App_Data/ban.txt


File diff suppressed because it is too large
+ 0 - 0
src/Masuit.MyBlogs.Core/App_Data/mod.txt


+ 2 - 4
src/Masuit.MyBlogs.Core/Common/CommonHelper.cs

@@ -159,10 +159,8 @@ namespace Masuit.MyBlogs.Core.Common
 
 
         public static string GetIPLocation(this string ip)
         public static string GetIPLocation(this string ip)
         {
         {
-            using (var searcher = new DbSearcher(Path.Combine(AppContext.BaseDirectory + "App_Data", "ip2region.db")))
-            {
-                return searcher.MemorySearch(ip).Region;
-            }
+            using var searcher = new DbSearcher(Path.Combine(AppContext.BaseDirectory + "App_Data", "ip2region.db"));
+            return searcher.MemorySearch(ip).Region;
         }
         }
 
 
         /// <summary>
         /// <summary>

+ 63 - 77
src/Masuit.MyBlogs.Core/Common/ImagebedClient.cs

@@ -73,17 +73,15 @@ namespace Masuit.MyBlogs.Core.Common
         {
         {
             string base64String = Convert.ToBase64String(stream.ToByteArray());
             string base64String = Convert.ToBase64String(stream.ToByteArray());
             string path = $"{DateTime.Now:yyyyMMdd}/{Path.GetFileName(file)}";
             string path = $"{DateTime.Now:yyyyMMdd}/{Path.GetFileName(file)}";
-            using (var resp = await _httpClient.PostAsJsonAsync(AppConfig.GiteeConfig.ApiUrl + HttpUtility.UrlEncode(path), new
+            using var resp = await _httpClient.PostAsJsonAsync(AppConfig.GiteeConfig.ApiUrl + HttpUtility.UrlEncode(path), new
             {
             {
                 access_token = AppConfig.GiteeConfig.AccessToken,
                 access_token = AppConfig.GiteeConfig.AccessToken,
                 content = base64String,
                 content = base64String,
                 message = "上传一张图片"
                 message = "上传一张图片"
-            }))
+            });
+            if (resp.IsSuccessStatusCode || (await resp.Content.ReadAsStringAsync()).Contains("already exists"))
             {
             {
-                if (resp.IsSuccessStatusCode || (await resp.Content.ReadAsStringAsync()).Contains("already exists"))
-                {
-                    return (AppConfig.GiteeConfig.RawUrl + path, true);
-                }
+                return (AppConfig.GiteeConfig.RawUrl + path, true);
             }
             }
 
 
             return AppConfig.AliOssConfig.Enabled ? await UploadOss(stream, file) : await UploadSmms(stream, file);
             return AppConfig.AliOssConfig.Enabled ? await UploadOss(stream, file) : await UploadSmms(stream, file);
@@ -106,7 +104,7 @@ namespace Masuit.MyBlogs.Core.Common
             string base64String = Convert.ToBase64String(stream.ToByteArray());
             string base64String = Convert.ToBase64String(stream.ToByteArray());
             _httpClient.DefaultRequestHeaders.Add("PRIVATE-TOKEN", gitlab.AccessToken);
             _httpClient.DefaultRequestHeaders.Add("PRIVATE-TOKEN", gitlab.AccessToken);
             string path = $"{DateTime.Now:yyyyMMdd}/{Path.GetFileName(file)}";
             string path = $"{DateTime.Now:yyyyMMdd}/{Path.GetFileName(file)}";
-            using (var resp = await _httpClient.PostAsJsonAsync(gitlab.ApiUrl.Contains("/v3/") ? gitlab.ApiUrl : gitlab.ApiUrl + HttpUtility.UrlEncode(path), new
+            using var resp = await _httpClient.PostAsJsonAsync(gitlab.ApiUrl.Contains("/v3/") ? gitlab.ApiUrl : gitlab.ApiUrl + HttpUtility.UrlEncode(path), new
             {
             {
                 file_path = path,
                 file_path = path,
                 branch_name = gitlab.Branch,
                 branch_name = gitlab.Branch,
@@ -116,12 +114,10 @@ namespace Masuit.MyBlogs.Core.Common
                 encoding = "base64",
                 encoding = "base64",
                 content = base64String,
                 content = base64String,
                 commit_message = "上传一张图片"
                 commit_message = "上传一张图片"
-            }))
+            });
+            if (resp.IsSuccessStatusCode || (await resp.Content.ReadAsStringAsync()).Contains("already exists"))
             {
             {
-                if (resp.IsSuccessStatusCode || (await resp.Content.ReadAsStringAsync()).Contains("already exists"))
-                {
-                    return (gitlab.RawUrl + path, true);
-                }
+                return (gitlab.RawUrl + path, true);
             }
             }
 
 
             return AppConfig.AliOssConfig.Enabled ? await UploadOss(stream, file) : await UploadSmms(stream, file);
             return AppConfig.AliOssConfig.Enabled ? await UploadOss(stream, file) : await UploadSmms(stream, file);
@@ -154,45 +150,41 @@ namespace Masuit.MyBlogs.Core.Common
             string url = string.Empty;
             string url = string.Empty;
             bool success = false;
             bool success = false;
             _httpClient.DefaultRequestHeaders.UserAgent.Add(ProductInfoHeaderValue.Parse("Mozilla/5.0"));
             _httpClient.DefaultRequestHeaders.UserAgent.Add(ProductInfoHeaderValue.Parse("Mozilla/5.0"));
-            using (var bc = new StreamContent(stream))
+            using var bc = new StreamContent(stream);
+            bc.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
             {
             {
-                bc.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
-                {
-                    FileName = Path.GetFileName(file),
-                    Name = "smfile"
-                };
-                using (var content = new MultipartFormDataContent { bc })
+                FileName = Path.GetFileName(file),
+                Name = "smfile"
+            };
+            using var content = new MultipartFormDataContent { bc };
+            var code = await _httpClient.PostAsync("https://sm.ms/api/upload?inajax=1&ssl=1", content).ContinueWith(t =>
+            {
+                if (t.IsCanceled || t.IsFaulted)
                 {
                 {
-                    var code = await _httpClient.PostAsync("https://sm.ms/api/upload?inajax=1&ssl=1", content).ContinueWith(t =>
-                    {
-                        if (t.IsCanceled || t.IsFaulted)
-                        {
-                            return 0;
-                        }
+                    return 0;
+                }
 
 
-                        var res = t.Result;
-                        if (!res.IsSuccessStatusCode)
-                        {
-                            return 2;
-                        }
+                var res = t.Result;
+                if (!res.IsSuccessStatusCode)
+                {
+                    return 2;
+                }
 
 
-                        try
-                        {
-                            string s = res.Content.ReadAsStringAsync().Result;
-                            var token = JObject.Parse(s);
-                            url = (string)token["data"]["url"];
-                            return 1;
-                        }
-                        catch
-                        {
-                            return 2;
-                        }
-                    });
-                    if (code == 1)
-                    {
-                        success = true;
-                    }
+                try
+                {
+                    string s = res.Content.ReadAsStringAsync().Result;
+                    var token = JObject.Parse(s);
+                    url = (string)token["data"]["url"];
+                    return 1;
+                }
+                catch
+                {
+                    return 2;
                 }
                 }
+            });
+            if (code == 1)
+            {
+                success = true;
             }
             }
 
 
             return success ? (url, true) : await UploadPeople(stream, file);
             return success ? (url, true) : await UploadPeople(stream, file);
@@ -208,36 +200,32 @@ namespace Masuit.MyBlogs.Core.Common
         {
         {
             bool success = false;
             bool success = false;
             _httpClient.DefaultRequestHeaders.UserAgent.Add(ProductInfoHeaderValue.Parse("Chrome/72.0.3626.96"));
             _httpClient.DefaultRequestHeaders.UserAgent.Add(ProductInfoHeaderValue.Parse("Chrome/72.0.3626.96"));
-            using (var sc = new StreamContent(stream))
+            using var sc = new StreamContent(stream);
+            using var mc = new MultipartFormDataContent
             {
             {
-                using (var mc = new MultipartFormDataContent
-                {
-                    { sc, "Filedata", Path.GetFileName(file) },
-                    {new StringContent("."+Path.GetExtension(file)),"filetype"}
-                })
+                { sc, "Filedata", Path.GetFileName(file) },
+                {new StringContent("."+Path.GetExtension(file)),"filetype"}
+            };
+            var str = await _httpClient.PostAsync("http://bbs1.people.com.cn/postImageUpload.do", mc).ContinueWith(t =>
+            {
+                if (t.IsCompletedSuccessfully)
                 {
                 {
-                    var str = await _httpClient.PostAsync("http://bbs1.people.com.cn/postImageUpload.do", mc).ContinueWith(t =>
+                    var res = t.Result;
+                    if (res.IsSuccessStatusCode)
                     {
                     {
-                        if (t.IsCompletedSuccessfully)
+                        string result = res.Content.ReadAsStringAsync().Result;
+                        string url = "http://bbs1.people.com.cn" + (string)JObject.Parse(result)["imageUrl"];
+                        if (url.EndsWith(Path.GetExtension(file)))
                         {
                         {
-                            var res = t.Result;
-                            if (res.IsSuccessStatusCode)
-                            {
-                                string result = res.Content.ReadAsStringAsync().Result;
-                                string url = "http://bbs1.people.com.cn" + (string)JObject.Parse(result)["imageUrl"];
-                                if (url.EndsWith(Path.GetExtension(file)))
-                                {
-                                    success = true;
-                                    return url;
-                                }
-                            }
+                            success = true;
+                            return url;
                         }
                         }
-
-                        return "";
-                    });
-                    return (str, success);
+                    }
                 }
                 }
-            }
+
+                return "";
+            });
+            return (str, success);
         }
         }
 
 
         /// <summary>
         /// <summary>
@@ -261,14 +249,12 @@ namespace Masuit.MyBlogs.Core.Common
                     continue;
                     continue;
                 }
                 }
 
 
-                using (var stream = File.OpenRead(path))
+                await using var stream = File.OpenRead(path);
+                var (url, success) = await UploadImage(stream, path);
+                if (success)
                 {
                 {
-                    var (url, success) = await UploadImage(stream, path);
-                    if (success)
-                    {
-                        content = content.Replace(src, url);
-                        BackgroundJob.Enqueue(() => File.Delete(path));
-                    }
+                    content = content.Replace(src, url);
+                    BackgroundJob.Enqueue(() => File.Delete(path));
                 }
                 }
             }
             }
 
 

+ 2 - 4
src/Masuit.MyBlogs.Core/Controllers/FileController.cs

@@ -87,10 +87,8 @@ namespace Masuit.MyBlogs.Core.Controllers
                 foreach (var t in Request.Form.Files)
                 foreach (var t in Request.Form.Files)
                 {
                 {
                     string path = Path.Combine(HostEnvironment.ContentRootPath, CommonHelper.SystemSettings["PathRoot"].TrimStart('\\', '/'), destination.TrimStart('\\', '/'), t.FileName);
                     string path = Path.Combine(HostEnvironment.ContentRootPath, CommonHelper.SystemSettings["PathRoot"].TrimStart('\\', '/'), destination.TrimStart('\\', '/'), t.FileName);
-                    using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
-                    {
-                        t.CopyTo(fs);
-                    }
+                    using var fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite);
+                    t.CopyTo(fs);
                 }
                 }
             }
             }
             return Json(new
             return Json(new

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

@@ -194,7 +194,7 @@ namespace Masuit.MyBlogs.Core.Controllers
         /// <returns></returns>
         /// <returns></returns>
         public ActionResult Publish()
         public ActionResult Publish()
         {
         {
-            var list = PostService.GetQuery(p => !string.IsNullOrEmpty(p.Label)).Select(p => p.Label).Distinct().SelectMany(s => s.Split(',', ',')).OrderBy(s => s).Cacheable().ToHashSet();
+            var list = PostService.GetQuery(p => !string.IsNullOrEmpty(p.Label)).Select(p => p.Label).Distinct().Cacheable().AsParallel().SelectMany(s => s.Split(',', ',')).OrderBy(s => s).ToHashSet();
             ViewBag.Category = CategoryService.GetQueryFromCache(c => c.Status == Status.Available).ToList();
             ViewBag.Category = CategoryService.GetQueryFromCache(c => c.Status == Status.Available).ToList();
             return View(list);
             return View(list);
         }
         }
@@ -517,8 +517,7 @@ namespace Masuit.MyBlogs.Core.Controllers
         {
         {
             var post = PostService.GetById(id);
             var post = PostService.GetById(id);
             post.Status = Status.Deleted;
             post.Status = Status.Deleted;
-            bool b = SearchEngine.SaveChanges() > 0;
-            SearchEngine.LuceneIndexer.Delete(post);
+            bool b = PostService.SaveChanges(true) > 0;
             return ResultData(null, b, b ? "删除成功!" : "删除失败!");
             return ResultData(null, b, b ? "删除成功!" : "删除失败!");
         }
         }
 
 

+ 0 - 7
src/Masuit.MyBlogs.Core/Controllers/SearchController.cs

@@ -5,12 +5,10 @@ using Masuit.MyBlogs.Core.Infrastructure.Services.Interface;
 using Masuit.MyBlogs.Core.Models.DTO;
 using Masuit.MyBlogs.Core.Models.DTO;
 using Masuit.MyBlogs.Core.Models.Entity;
 using Masuit.MyBlogs.Core.Models.Entity;
 using Microsoft.AspNetCore.Mvc;
 using Microsoft.AspNetCore.Mvc;
-using Microsoft.Net.Http.Headers;
 using System;
 using System;
 using System.Collections.Generic;
 using System.Collections.Generic;
 using System.Linq;
 using System.Linq;
 using System.Linq.Expressions;
 using System.Linq.Expressions;
-using System.Text.RegularExpressions;
 
 
 namespace Masuit.MyBlogs.Core.Controllers
 namespace Masuit.MyBlogs.Core.Controllers
 {
 {
@@ -42,11 +40,6 @@ namespace Masuit.MyBlogs.Core.Controllers
             ViewBag.Total = 0;
             ViewBag.Total = 0;
             ViewBag.PageSize = size;
             ViewBag.PageSize = size;
             ViewBag.Keyword = wd;
             ViewBag.Keyword = wd;
-            if (Regex.Match(wd ?? "", CommonHelper.BanRegex).Length + Regex.Match(wd ?? "", CommonHelper.ModRegex).Length > 0)
-            {
-                return RedirectToAction("Search", "Search", new { wd = "" });
-            }
-
             string ip = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
             string ip = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
             string key = "Search:" + ip;
             string key = "Search:" + ip;
             if (CacheManager.Exists(key))
             if (CacheManager.Exists(key))

+ 19 - 23
src/Masuit.MyBlogs.Core/Controllers/ToolsController.cs

@@ -2,7 +2,6 @@
 using Masuit.Tools.Core.Net;
 using Masuit.Tools.Core.Net;
 using Masuit.Tools.Models;
 using Masuit.Tools.Models;
 using Microsoft.AspNetCore.Mvc;
 using Microsoft.AspNetCore.Mvc;
-using Microsoft.Net.Http.Headers;
 using Newtonsoft.Json;
 using Newtonsoft.Json;
 using System;
 using System;
 using System.Net.Http;
 using System.Net.Http;
@@ -60,15 +59,14 @@ namespace Masuit.MyBlogs.Core.Controllers
                 PhysicsAddress address = await ip.GetPhysicsAddressInfo();
                 PhysicsAddress address = await ip.GetPhysicsAddressInfo();
                 return View(address);
                 return View(address);
             }
             }
-            using (HttpClient client = new HttpClient()
+
+            using var client = new HttpClient()
             {
             {
                 BaseAddress = new Uri("http://api.map.baidu.com")
                 BaseAddress = new Uri("http://api.map.baidu.com")
-            })
-            {
-                var s = await client.GetStringAsync($"/geocoder/v2/?location={lat},{lng}&output=json&pois=1&ak={AppConfig.BaiduAK}");
-                PhysicsAddress physicsAddress = JsonConvert.DeserializeObject<PhysicsAddress>(s);
-                return View(physicsAddress);
-            }
+            };
+            var s = await client.GetStringAsync($"/geocoder/v2/?location={lat},{lng}&output=json&pois=1&ak={AppConfig.BaiduAK}");
+            var physicsAddress = JsonConvert.DeserializeObject<PhysicsAddress>(s);
+            return View(physicsAddress);
         }
         }
 
 
         /// <summary>
         /// <summary>
@@ -86,7 +84,7 @@ namespace Masuit.MyBlogs.Core.Controllers
                 Random r = new Random();
                 Random r = new Random();
                 ip = $"{r.Next(210)}.{r.Next(255)}.{r.Next(255)}.{r.Next(255)}";
                 ip = $"{r.Next(210)}.{r.Next(255)}.{r.Next(255)}.{r.Next(255)}";
 #endif
 #endif
-                PhysicsAddress address = await ip.GetPhysicsAddressInfo();
+                var address = await ip.GetPhysicsAddressInfo();
                 if (address?.Status == 0)
                 if (address?.Status == 0)
                 {
                 {
                     ViewBag.Address = address.AddressResult.FormattedAddress;
                     ViewBag.Address = address.AddressResult.FormattedAddress;
@@ -98,26 +96,24 @@ namespace Masuit.MyBlogs.Core.Controllers
                 }
                 }
             }
             }
             ViewBag.Address = addr;
             ViewBag.Address = addr;
-            using (HttpClient client = new HttpClient()
+            using HttpClient client = new HttpClient()
             {
             {
                 BaseAddress = new Uri("http://api.map.baidu.com")
                 BaseAddress = new Uri("http://api.map.baidu.com")
-            })
+            };
+            var s = await client.GetStringAsync($"/geocoder/v2/?output=json&address={addr}&ak={AppConfig.BaiduAK}");
+            var physicsAddress = JsonConvert.DeserializeAnonymousType(s, new
             {
             {
-                var s = await client.GetStringAsync($"/geocoder/v2/?output=json&address={addr}&ak={AppConfig.BaiduAK}");
-                var physicsAddress = JsonConvert.DeserializeAnonymousType(s, new
+                status = 0,
+                result = new
                 {
                 {
-                    status = 0,
-                    result = new
-                    {
-                        location = new Location()
-                    }
-                });
-                if (Request.Method.ToLower().Equals("get"))
-                {
-                    return View(physicsAddress.result.location);
+                    location = new Location()
                 }
                 }
-                return Json(physicsAddress.result.location);
+            });
+            if (Request.Method.ToLower().Equals("get"))
+            {
+                return View(physicsAddress.result.location);
             }
             }
+            return Json(physicsAddress.result.location);
         }
         }
     }
     }
 }
 }

+ 4 - 6
src/Masuit.MyBlogs.Core/Controllers/UploadController.cs

@@ -96,10 +96,8 @@ namespace Masuit.MyBlogs.Core.Controllers
             string resourceName = string.Empty.CreateShortToken(9);
             string resourceName = string.Empty.CreateShortToken(9);
             string ext = Path.GetExtension(fileName);
             string ext = Path.GetExtension(fileName);
             string docPath = Path.Combine(upload, resourceName + ext);
             string docPath = Path.Combine(upload, resourceName + ext);
-            using (FileStream fs = new FileStream(docPath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
-            {
-                file.CopyTo(fs);
-            }
+            using var fs = new FileStream(docPath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
+            file.CopyTo(fs);
             string htmlDir = docPath.Replace(".docx", "").Replace(".doc", "");
             string htmlDir = docPath.Replace(".docx", "").Replace(".doc", "");
             DocumentConvert.Doc2Html(docPath, htmlDir);
             DocumentConvert.Doc2Html(docPath, htmlDir);
             string htmlfile = Path.Combine(htmlDir, "index.html");
             string htmlfile = Path.Combine(htmlDir, "index.html");
@@ -248,7 +246,7 @@ namespace Masuit.MyBlogs.Core.Controllers
                         Directory.CreateDirectory(dir);
                         Directory.CreateDirectory(dir);
                     }
                     }
 
 
-                    using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
+                    await using (var fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                     {
                     {
                         file.CopyTo(fs);
                         file.CopyTo(fs);
                     }
                     }
@@ -272,7 +270,7 @@ namespace Masuit.MyBlogs.Core.Controllers
                     Directory.CreateDirectory(dir);
                     Directory.CreateDirectory(dir);
                 }
                 }
 
 
-                using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
+                await using (var fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                 {
                 {
                     file.CopyTo(fs);
                     file.CopyTo(fs);
                 }
                 }

+ 18 - 9
src/Masuit.MyBlogs.Core/Extensions/FirewallAttribute.cs

@@ -5,11 +5,13 @@ using Masuit.MyBlogs.Core.Configs;
 using Masuit.MyBlogs.Core.Extensions.Hangfire;
 using Masuit.MyBlogs.Core.Extensions.Hangfire;
 using Masuit.Tools.Core.Net;
 using Masuit.Tools.Core.Net;
 using Masuit.Tools.Security;
 using Masuit.Tools.Security;
+using Microsoft.AspNetCore.Http;
 using Microsoft.AspNetCore.Mvc;
 using Microsoft.AspNetCore.Mvc;
 using Microsoft.AspNetCore.Mvc.Filters;
 using Microsoft.AspNetCore.Mvc.Filters;
 using Microsoft.Net.Http.Headers;
 using Microsoft.Net.Http.Headers;
 using System;
 using System;
 using System.Linq;
 using System.Linq;
+using System.Text;
 using System.Web;
 using System.Web;
 
 
 namespace Masuit.MyBlogs.Core.Extensions
 namespace Masuit.MyBlogs.Core.Extensions
@@ -41,14 +43,7 @@ namespace Masuit.MyBlogs.Core.Extensions
             var ip = context.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
             var ip = context.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
             if (ip.IsDenyIpAddress() && string.IsNullOrEmpty(context.HttpContext.Session.Get<string>("FullAccessViewToken")))
             if (ip.IsDenyIpAddress() && string.IsNullOrEmpty(context.HttpContext.Session.Get<string>("FullAccessViewToken")))
             {
             {
-                BackgroundJob.Enqueue(() => HangfireBackJob.InterceptLog(new IpIntercepter()
-                {
-                    IP = ip,
-                    RequestUrl = HttpUtility.UrlDecode(request.Scheme + "://" + request.Host + request.Path),
-                    Time = DateTime.Now,
-                    UserAgent = request.Headers[HeaderNames.UserAgent]
-                }));
-                context.Result = new RedirectToActionResult("AccessDeny", "Error", null);
+                AccessDeny(context, ip, request);
                 return;
                 return;
             }
             }
 
 
@@ -68,10 +63,11 @@ namespace Masuit.MyBlogs.Core.Extensions
             if (times > limit * 1.2)
             if (times > limit * 1.2)
             {
             {
                 CacheManager.Expire("Frequency:" + ip, ExpirationMode.Sliding, TimeSpan.FromMinutes(CommonHelper.SystemSettings.GetOrAdd("BanIPTimespan", "10").ToInt32()));
                 CacheManager.Expire("Frequency:" + ip, ExpirationMode.Sliding, TimeSpan.FromMinutes(CommonHelper.SystemSettings.GetOrAdd("BanIPTimespan", "10").ToInt32()));
+                var path = HttpUtility.UrlDecode(request.Path + request.QueryString, Encoding.UTF8);
                 BackgroundJob.Enqueue(() => HangfireBackJob.InterceptLog(new IpIntercepter()
                 BackgroundJob.Enqueue(() => HangfireBackJob.InterceptLog(new IpIntercepter()
                 {
                 {
                     IP = ip,
                     IP = ip,
-                    RequestUrl = HttpUtility.UrlDecode(request.Scheme + "://" + request.Host + request.Path),
+                    RequestUrl = HttpUtility.UrlDecode(request.Scheme + "://" + request.Host + path),
                     Time = DateTime.Now,
                     Time = DateTime.Now,
                     UserAgent = request.Headers[HeaderNames.UserAgent]
                     UserAgent = request.Headers[HeaderNames.UserAgent]
                 }));
                 }));
@@ -79,5 +75,18 @@ namespace Masuit.MyBlogs.Core.Extensions
 
 
             context.Result = new RedirectResult("/tempdeny");
             context.Result = new RedirectResult("/tempdeny");
         }
         }
+
+        private void AccessDeny(ActionExecutingContext context, string ip, HttpRequest request)
+        {
+            var path = HttpUtility.UrlDecode(request.Path + request.QueryString, Encoding.UTF8);
+            BackgroundJob.Enqueue(() => HangfireBackJob.InterceptLog(new IpIntercepter()
+            {
+                IP = ip,
+                RequestUrl = HttpUtility.UrlDecode(request.Scheme + "://" + request.Host + path),
+                Time = DateTime.Now,
+                UserAgent = request.Headers[HeaderNames.UserAgent]
+            }));
+            context.Result = new RedirectToActionResult("AccessDeny", "Error", null);
+        }
     }
     }
 }
 }

+ 2 - 4
src/Masuit.MyBlogs.Core/Extensions/Hangfire/HangfireBackJob.cs

@@ -145,10 +145,8 @@ namespace Masuit.MyBlogs.Core.Extensions.Hangfire
             }
             }
             else
             else
             {
             {
-                using (DbSearcher searcher = new DbSearcher(Path.Combine(AppContext.BaseDirectory + "App_Data", "ip2region.db")))
-                {
-                    s.Address = searcher.MemorySearch(s.IP).Region;
-                }
+                using var searcher = new DbSearcher(Path.Combine(AppContext.BaseDirectory + "App_Data", "ip2region.db"));
+                s.Address = searcher.MemorySearch(s.IP).Region;
             }
             }
             RedisHelper.LPush("intercept", s);
             RedisHelper.LPush("intercept", s);
         }
         }

+ 1 - 10
src/Masuit.MyBlogs.Core/Extensions/MiddlewareExtension.cs

@@ -54,20 +54,11 @@ namespace Masuit.MyBlogs.Core.Extensions
         /// <returns></returns>
         /// <returns></returns>
         public static IServiceCollection AddMyMvc(this IServiceCollection services)
         public static IServiceCollection AddMyMvc(this IServiceCollection services)
         {
         {
-            services.AddControllers(options =>
-            {
-                options.Filters.Add<MyExceptionFilter>();
-            }).AddControllersAsServices(); // WebAPI
-            services.AddControllersWithViews(options =>
-            {
-                options.Filters.Add<MyExceptionFilter>();
-            }).AddNewtonsoftJson(options =>
+            services.AddMvc().AddNewtonsoftJson(options =>
             {
             {
                 options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                 options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                 options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc; // 设置时区为 UTC
                 options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc; // 设置时区为 UTC
             }).AddControllersAsServices().AddViewComponentsAsServices().AddTagHelpersAsServices(); // MVC
             }).AddControllersAsServices().AddViewComponentsAsServices().AddTagHelpersAsServices(); // MVC
-            services.AddRazorPages().AddViewComponentsAsServices().AddTagHelpersAsServices(); // RazorPage
-
             services.Configure<WebEncoderOptions>(options =>
             services.Configure<WebEncoderOptions>(options =>
             {
             {
                 options.TextEncoderSettings = new TextEncoderSettings(UnicodeRanges.All);
                 options.TextEncoderSettings = new TextEncoderSettings(UnicodeRanges.All);

+ 21 - 1
src/Masuit.MyBlogs.Core/Extensions/RequestInterceptMiddleware.cs

@@ -1,4 +1,5 @@
-using Masuit.MyBlogs.Core.Common;
+using Hangfire;
+using Masuit.MyBlogs.Core.Common;
 using Masuit.MyBlogs.Core.Extensions.Hangfire;
 using Masuit.MyBlogs.Core.Extensions.Hangfire;
 using Masuit.Tools;
 using Masuit.Tools;
 using Masuit.Tools.Core.Net;
 using Masuit.Tools.Core.Net;
@@ -6,7 +7,9 @@ using Microsoft.AspNetCore.Http;
 using Microsoft.Net.Http.Headers;
 using Microsoft.Net.Http.Headers;
 using System;
 using System;
 using System.Text;
 using System.Text;
+using System.Text.RegularExpressions;
 using System.Threading.Tasks;
 using System.Threading.Tasks;
+using System.Web;
 
 
 namespace Masuit.MyBlogs.Core.Extensions
 namespace Masuit.MyBlogs.Core.Extensions
 {
 {
@@ -28,6 +31,22 @@ namespace Masuit.MyBlogs.Core.Extensions
 
 
         public async Task Invoke(HttpContext context)
         public async Task Invoke(HttpContext context)
         {
         {
+            var request = context.Request;
+            var path = HttpUtility.UrlDecode(request.Path + request.QueryString, Encoding.UTF8);
+            if (Regex.Match(path ?? "", CommonHelper.BanRegex).Length > 0)
+            {
+                BackgroundJob.Enqueue(() => HangfireBackJob.InterceptLog(new IpIntercepter()
+                {
+                    IP = context.Connection.RemoteIpAddress.MapToIPv4().ToString(),
+                    RequestUrl = HttpUtility.UrlDecode(request.Scheme + "://" + request.Host + path),
+                    Time = DateTime.Now,
+                    UserAgent = request.Headers[HeaderNames.UserAgent]
+                }));
+                context.Response.StatusCode = 504;
+                await context.Response.WriteAsync("参数不合法!", Encoding.UTF8);
+                return;
+            }
+
             if (!context.Session.TryGetValue("session", out _) && !context.Request.IsRobot())
             if (!context.Session.TryGetValue("session", out _) && !context.Request.IsRobot())
             {
             {
                 context.Session.Set("session", 0);
                 context.Session.Set("session", 0);
@@ -45,6 +64,7 @@ namespace Masuit.MyBlogs.Core.Extensions
                     }
                     }
                     catch
                     catch
                     {
                     {
+                        context.Response.StatusCode = 504;
                         await context.Response.WriteAsync("您的浏览器不支持访问本站!", Encoding.UTF8);
                         await context.Response.WriteAsync("您的浏览器不支持访问本站!", Encoding.UTF8);
                         return;
                         return;
                     }
                     }

+ 14 - 17
src/Masuit.MyBlogs.Core/Extensions/UEditor/CrawlerHandler.cs

@@ -73,26 +73,23 @@ namespace Masuit.MyBlogs.Core.Extensions.UEditor
 
 
             try
             try
             {
             {
-                using (var stream = response.Content.ReadAsStreamAsync().Result)
+                using var stream = response.Content.ReadAsStreamAsync().Result;
+                var savePath = AppContext.BaseDirectory + "wwwroot" + ServerUrl;
+                var (url, success) = Startup.ServiceProvider.GetRequiredService<ImagebedClient>().UploadImage(stream, savePath).Result;
+                if (success)
                 {
                 {
-                    var savePath = AppContext.BaseDirectory + "wwwroot" + ServerUrl;
-                    var (url, success) = Startup.ServiceProvider.GetRequiredService<ImagebedClient>().UploadImage(stream, savePath).Result;
-                    if (success)
-                    {
-                        ServerUrl = url;
-                    }
-                    else
+                    ServerUrl = url;
+                }
+                else
+                {
+                    if (!Directory.Exists(Path.GetDirectoryName(savePath)))
                     {
                     {
-                        if (!Directory.Exists(Path.GetDirectoryName(savePath)))
-                        {
-                            Directory.CreateDirectory(Path.GetDirectoryName(savePath));
-                        }
-                        using (var ms = new MemoryStream())
-                        {
-                            stream.CopyTo(ms);
-                            File.WriteAllBytes(savePath, ms.GetBuffer());
-                        }
+                        Directory.CreateDirectory(Path.GetDirectoryName(savePath));
                     }
                     }
+
+                    using var ms = new MemoryStream();
+                    stream.CopyTo(ms);
+                    File.WriteAllBytes(savePath, ms.GetBuffer());
                 }
                 }
 
 
                 State = "SUCCESS";
                 State = "SUCCESS";

+ 1 - 1
src/Masuit.MyBlogs.Core/Extensions/UEditor/PathFormatter.cs

@@ -23,7 +23,7 @@ namespace Masuit.MyBlogs.Core.Extensions.UEditor
             string filename = Path.GetFileNameWithoutExtension(originFileName);
             string filename = Path.GetFileNameWithoutExtension(originFileName);
 
 
             pathFormat = pathFormat.Replace("{filename}", filename);
             pathFormat = pathFormat.Replace("{filename}", filename);
-            pathFormat = new Regex(@"\{rand(\:?)(\d+)\}", RegexOptions.Compiled).Replace(pathFormat, match =>
+            pathFormat = new Regex(@"\{rand(\:?)(\d+)\}").Replace(pathFormat, match =>
             {
             {
                 var digit = 6;
                 var digit = 6;
                 if (match.Groups.Count > 2)
                 if (match.Groups.Count > 2)

+ 11 - 13
src/Masuit.MyBlogs.Core/Extensions/UEditor/UploadHandler.cs

@@ -47,23 +47,21 @@ namespace Masuit.MyBlogs.Core.Extensions.UEditor
             {
             {
                 if (UploadConfig.AllowExtensions.Contains(Path.GetExtension(uploadFileName)))
                 if (UploadConfig.AllowExtensions.Contains(Path.GetExtension(uploadFileName)))
                 {
                 {
-                    using (Stream stream = file.OpenReadStream())
+                    using var stream = file.OpenReadStream();
+                    var (url, success) = Startup.ServiceProvider.GetRequiredService<ImagebedClient>().UploadImage(stream, localPath).Result;
+                    if (success)
                     {
                     {
-                        var (url, success) = Startup.ServiceProvider.GetRequiredService<ImagebedClient>().UploadImage(stream, localPath).Result;
-                        if (success)
+                        Result.Url = url;
+                    }
+                    else
+                    {
+                        if (!Directory.Exists(Path.GetDirectoryName(localPath)))
                         {
                         {
-                            Result.Url = url;
+                            Directory.CreateDirectory(Path.GetDirectoryName(localPath));
                         }
                         }
-                        else
-                        {
-                            if (!Directory.Exists(Path.GetDirectoryName(localPath)))
-                            {
-                                Directory.CreateDirectory(Path.GetDirectoryName(localPath));
-                            }
 
 
-                            File.WriteAllBytes(localPath, stream.ToByteArray());
-                            Result.Url = savePath;
-                        }
+                        File.WriteAllBytes(localPath, stream.ToByteArray());
+                        Result.Url = savePath;
                     }
                     }
                 }
                 }
                 else
                 else

+ 13 - 0
src/Masuit.MyBlogs.Core/Infrastructure/Services/Interface/IPostService.cs

@@ -1,10 +1,23 @@
 using Masuit.MyBlogs.Core.Models.DTO;
 using Masuit.MyBlogs.Core.Models.DTO;
 using Masuit.MyBlogs.Core.Models.Entity;
 using Masuit.MyBlogs.Core.Models.Entity;
+using System.Threading.Tasks;
 
 
 namespace Masuit.MyBlogs.Core.Infrastructure.Services.Interface
 namespace Masuit.MyBlogs.Core.Infrastructure.Services.Interface
 {
 {
     public partial interface IPostService : IBaseService<Post>
     public partial interface IPostService : IBaseService<Post>
     {
     {
         SearchResult<PostOutputDto> SearchPage(int page, int size, string keyword);
         SearchResult<PostOutputDto> SearchPage(int page, int size, string keyword);
+
+        /// <summary>
+        /// 统一保存的方法
+        /// </summary>
+        /// <returns>受影响的行数</returns>
+        int SaveChanges(bool flushIndex);
+
+        /// <summary>
+        /// 统一保存数据
+        /// </summary>
+        /// <returns>受影响的行数</returns>
+        Task<int> SaveChangesAsync(bool flushIndex);
     }
     }
 }
 }

+ 4 - 4
src/Masuit.MyBlogs.Core/Infrastructure/Services/PostService.cs

@@ -215,18 +215,18 @@ namespace Masuit.MyBlogs.Core.Infrastructure.Services
         /// 统一保存的方法
         /// 统一保存的方法
         /// </summary>
         /// </summary>
         /// <returns>受影响的行数</returns>
         /// <returns>受影响的行数</returns>
-        public override int SaveChanges()
+        public int SaveChanges(bool flushIndex)
         {
         {
-            return _searchEngine.SaveChanges();
+            return flushIndex ? _searchEngine.SaveChanges() : base.SaveChanges();
         }
         }
 
 
         /// <summary>
         /// <summary>
         /// 统一保存数据
         /// 统一保存数据
         /// </summary>
         /// </summary>
         /// <returns>受影响的行数</returns>
         /// <returns>受影响的行数</returns>
-        public override Task<int> SaveChangesAsync()
+        public async Task<int> SaveChangesAsync(bool flushIndex)
         {
         {
-            return _searchEngine.SaveChangesAsync();
+            return flushIndex ? await _searchEngine.SaveChangesAsync() : await base.SaveChangesAsync();
         }
         }
     }
     }
 }
 }

+ 2 - 1
src/Masuit.MyBlogs.Core/Masuit.MyBlogs.Core.csproj

@@ -54,7 +54,7 @@
     <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="7.0.0" />
     <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="7.0.0" />
     <PackageReference Include="CacheManager.Microsoft.Extensions.Caching.Memory" Version="2.0.0-beta-1629" />
     <PackageReference Include="CacheManager.Microsoft.Extensions.Caching.Memory" Version="2.0.0-beta-1629" />
     <PackageReference Include="CacheManager.Serialization.Json" Version="2.0.0-beta-1629" />
     <PackageReference Include="CacheManager.Serialization.Json" Version="2.0.0-beta-1629" />
-    <PackageReference Include="CSRedisCore" Version="3.1.8" />
+    <PackageReference Include="CSRedisCore" Version="3.1.10" />
     <PackageReference Include="EFSecondLevelCache.Core" Version="2.8.1" />
     <PackageReference Include="EFSecondLevelCache.Core" Version="2.8.1" />
     <PackageReference Include="Hangfire" Version="1.7.6" />
     <PackageReference Include="Hangfire" Version="1.7.6" />
     <PackageReference Include="Hangfire.Autofac" Version="2.3.1" />
     <PackageReference Include="Hangfire.Autofac" Version="2.3.1" />
@@ -63,6 +63,7 @@
     <PackageReference Include="htmldiff.net-core" Version="1.3.6" />
     <PackageReference Include="htmldiff.net-core" Version="1.3.6" />
     <PackageReference Include="IP2Region" Version="1.2.0" />
     <PackageReference Include="IP2Region" Version="1.2.0" />
     <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.0.0" />
     <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.0.0" />
+    <PackageReference Include="Microsoft.AspNetCore.SignalR.Protocols.NewtonsoftJson" Version="3.0.0" />
     <PackageReference Include="Microsoft.EntityFrameworkCore.Proxies" Version="3.0.0" />
     <PackageReference Include="Microsoft.EntityFrameworkCore.Proxies" Version="3.0.0" />
     <PackageReference Include="PanGu.HighLight" Version="1.0.0" />
     <PackageReference Include="PanGu.HighLight" Version="1.0.0" />
     <PackageReference Include="Polly" Version="7.1.1" />
     <PackageReference Include="Polly" Version="7.1.1" />

+ 1 - 1
src/Masuit.MyBlogs.Core/Properties/PublishProfiles/FolderProfile.pubxml

@@ -12,7 +12,7 @@
     <SiteUrlToLaunchAfterPublish />
     <SiteUrlToLaunchAfterPublish />
     <LaunchSiteAfterPublish>True</LaunchSiteAfterPublish>
     <LaunchSiteAfterPublish>True</LaunchSiteAfterPublish>
     <ExcludeApp_Data>False</ExcludeApp_Data>
     <ExcludeApp_Data>False</ExcludeApp_Data>
-    <TargetFramework>netcoreapp2.2</TargetFramework>
+    <TargetFramework>netcoreapp3.0</TargetFramework>
     <ProjectGuid>51a09bd3-ab54-4df9-ab8b-c68df0672c39</ProjectGuid>
     <ProjectGuid>51a09bd3-ab54-4df9-ab8b-c68df0672c39</ProjectGuid>
     <SelfContained>false</SelfContained>
     <SelfContained>false</SelfContained>
     <_IsPortable>true</_IsPortable>
     <_IsPortable>true</_IsPortable>

+ 9 - 14
src/Masuit.MyBlogs.Core/Startup.cs

@@ -93,7 +93,7 @@ namespace Masuit.MyBlogs.Core
                 options.MultipartBodyLengthLimit = 104857600; // 100MB
                 options.MultipartBodyLengthLimit = 104857600; // 100MB
             }); //配置请求长度
             }); //配置请求长度
             services.AddSession(); //注入Session
             services.AddSession(); //注入Session
-            services.AddWebSockets(opt => opt.ReceiveBufferSize = 4096 * 1024).AddSignalR();
+            services.AddWebSockets(opt => opt.ReceiveBufferSize = 4096 * 1024).AddSignalR().AddNewtonsoftJsonProtocol();
             services.AddHttpsRedirection(options =>
             services.AddHttpsRedirection(options =>
             {
             {
                 options.RedirectStatusCode = StatusCodes.Status301MovedPermanently;
                 options.RedirectStatusCode = StatusCodes.Status301MovedPermanently;
@@ -110,7 +110,6 @@ namespace Masuit.MyBlogs.Core
             services.AddHttpClient("", c => c.Timeout = TimeSpan.FromSeconds(30)); //注入HttpClient
             services.AddHttpClient("", c => c.Timeout = TimeSpan.FromSeconds(30)); //注入HttpClient
             services.AddTransient<ImagebedClient>();
             services.AddTransient<ImagebedClient>();
             services.AddHttpContextAccessor(); //注入静态HttpContext
             services.AddHttpContextAccessor(); //注入静态HttpContext
-
             services.AddMapper().AddAutofac().AddMyMvc();
             services.AddMapper().AddAutofac().AddMyMvc();
         }
         }
 
 
@@ -140,18 +139,21 @@ namespace Masuit.MyBlogs.Core
             }
             }
 
 
             //db.Database.Migrate();
             //db.Database.Migrate();
+            var dic = db.SystemSetting.ToDictionary(s => s.Name, s => s.Value); //初始化系统设置参数
+            foreach (var (key, value) in dic)
+            {
+                CommonHelper.SystemSettings.TryAdd(key, value);
+            }
 
 
             UseLuceneSearch(env, hangfire, luceneIndexerOptions);
             UseLuceneSearch(env, hangfire, luceneIndexerOptions);
-
-            app.UseResponseCompression();
             if (bool.Parse(Configuration["Https:Enabled"]))
             if (bool.Parse(Configuration["Https:Enabled"]))
             {
             {
                 app.UseHttpsRedirection().UseRewriter(new RewriteOptions().AddRedirectToNonWww()); // URL重写
                 app.UseHttpsRedirection().UseRewriter(new RewriteOptions().AddRedirectToNonWww()); // URL重写
             }
             }
 
 
-            app.UseStaticHttpContext(); //注入静态HttpContext对象
             app.UseSession().UseCookiePolicy(); //注入Session
             app.UseSession().UseCookiePolicy(); //注入Session
-
+            app.UseRequestIntercept(); //启用网站请求拦截
+            app.UseStaticHttpContext(); //注入静态HttpContext对象
             app.UseStaticFiles(new StaticFileOptions //静态资源缓存策略
             app.UseStaticFiles(new StaticFileOptions //静态资源缓存策略
             {
             {
                 OnPrepareResponse = context =>
                 OnPrepareResponse = context =>
@@ -162,13 +164,6 @@ namespace Masuit.MyBlogs.Core
                 ContentTypeProvider = new FileExtensionContentTypeProvider(MimeMapper.MimeTypes),
                 ContentTypeProvider = new FileExtensionContentTypeProvider(MimeMapper.MimeTypes),
             });
             });
 
 
-            app.UseRequestIntercept(); //启用网站防火墙
-            var dic = db.SystemSetting.ToDictionary(s => s.Name, s => s.Value); //初始化系统设置参数
-            foreach (var (key, value) in dic)
-            {
-                CommonHelper.SystemSettings.TryAdd(key, value);
-            }
-
             app.UseHangfireServer().UseHangfireDashboard("/taskcenter", new DashboardOptions()
             app.UseHangfireServer().UseHangfireDashboard("/taskcenter", new DashboardOptions()
             {
             {
                 Authorization = new[]
                 Authorization = new[]
@@ -178,7 +173,6 @@ namespace Masuit.MyBlogs.Core
             }); //配置hangfire
             }); //配置hangfire
             app.UseCors(builder => builder.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin()); //配置跨域
             app.UseCors(builder => builder.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin()); //配置跨域
             app.UseResponseCaching().UseResponseCompression(); //启动Response缓存
             app.UseResponseCaching().UseResponseCompression(); //启动Response缓存
-            HangfireJobInit.Start(); //初始化定时任务
             app.UseRouting(); // 放在 UseStaticFiles 之后
             app.UseRouting(); // 放在 UseStaticFiles 之后
             app.UseEndpoints(endpoints =>
             app.UseEndpoints(endpoints =>
            {
            {
@@ -186,6 +180,7 @@ namespace Masuit.MyBlogs.Core
                endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}"); // 默认路由
                endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}"); // 默认路由
                endpoints.MapHub<MyHub>("/hubs");
                endpoints.MapHub<MyHub>("/hubs");
            });
            });
+            HangfireJobInit.Start(); //初始化定时任务
         }
         }
 
 
         private static void UseLuceneSearch(IWebHostEnvironment env, IHangfireBackJob hangfire, LuceneIndexerOptions luceneIndexerOptions)
         private static void UseLuceneSearch(IWebHostEnvironment env, IHangfireBackJob hangfire, LuceneIndexerOptions luceneIndexerOptions)

Some files were not shown because too many files changed in this diff