1
0
懒得勤快 6 жил өмнө
parent
commit
742d23a0da
21 өөрчлөгдсөн 189 нэмэгдсэн , 199 устгасан
  1. 0 0
      src/Masuit.MyBlogs.Core/App_Data/ban.txt
  2. 0 0
      src/Masuit.MyBlogs.Core/App_Data/mod.txt
  3. 2 4
      src/Masuit.MyBlogs.Core/Common/CommonHelper.cs
  4. 63 77
      src/Masuit.MyBlogs.Core/Common/ImagebedClient.cs
  5. 2 4
      src/Masuit.MyBlogs.Core/Controllers/FileController.cs
  6. 2 3
      src/Masuit.MyBlogs.Core/Controllers/PostController.cs
  7. 0 7
      src/Masuit.MyBlogs.Core/Controllers/SearchController.cs
  8. 19 23
      src/Masuit.MyBlogs.Core/Controllers/ToolsController.cs
  9. 4 6
      src/Masuit.MyBlogs.Core/Controllers/UploadController.cs
  10. 18 9
      src/Masuit.MyBlogs.Core/Extensions/FirewallAttribute.cs
  11. 2 4
      src/Masuit.MyBlogs.Core/Extensions/Hangfire/HangfireBackJob.cs
  12. 1 10
      src/Masuit.MyBlogs.Core/Extensions/MiddlewareExtension.cs
  13. 21 1
      src/Masuit.MyBlogs.Core/Extensions/RequestInterceptMiddleware.cs
  14. 14 17
      src/Masuit.MyBlogs.Core/Extensions/UEditor/CrawlerHandler.cs
  15. 1 1
      src/Masuit.MyBlogs.Core/Extensions/UEditor/PathFormatter.cs
  16. 11 13
      src/Masuit.MyBlogs.Core/Extensions/UEditor/UploadHandler.cs
  17. 13 0
      src/Masuit.MyBlogs.Core/Infrastructure/Services/Interface/IPostService.cs
  18. 4 4
      src/Masuit.MyBlogs.Core/Infrastructure/Services/PostService.cs
  19. 2 1
      src/Masuit.MyBlogs.Core/Masuit.MyBlogs.Core.csproj
  20. 1 1
      src/Masuit.MyBlogs.Core/Properties/PublishProfiles/FolderProfile.pubxml
  21. 9 14
      src/Masuit.MyBlogs.Core/Startup.cs

Файлын зөрүү хэтэрхий том тул дарагдсан байна
+ 0 - 0
src/Masuit.MyBlogs.Core/App_Data/ban.txt


Файлын зөрүү хэтэрхий том тул дарагдсан байна
+ 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)
         {
-            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>

+ 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 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,
                 content = base64String,
                 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);
@@ -106,7 +104,7 @@ namespace Masuit.MyBlogs.Core.Common
             string base64String = Convert.ToBase64String(stream.ToByteArray());
             _httpClient.DefaultRequestHeaders.Add("PRIVATE-TOKEN", gitlab.AccessToken);
             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,
                 branch_name = gitlab.Branch,
@@ -116,12 +114,10 @@ namespace Masuit.MyBlogs.Core.Common
                 encoding = "base64",
                 content = base64String,
                 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);
@@ -154,45 +150,41 @@ namespace Masuit.MyBlogs.Core.Common
             string url = string.Empty;
             bool success = false;
             _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);
@@ -208,36 +200,32 @@ namespace Masuit.MyBlogs.Core.Common
         {
             bool success = false;
             _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>
@@ -261,14 +249,12 @@ namespace Masuit.MyBlogs.Core.Common
                     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)
                 {
                     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

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

@@ -194,7 +194,7 @@ namespace Masuit.MyBlogs.Core.Controllers
         /// <returns></returns>
         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();
             return View(list);
         }
@@ -517,8 +517,7 @@ namespace Masuit.MyBlogs.Core.Controllers
         {
             var post = PostService.GetById(id);
             post.Status = Status.Deleted;
-            bool b = SearchEngine.SaveChanges() > 0;
-            SearchEngine.LuceneIndexer.Delete(post);
+            bool b = PostService.SaveChanges(true) > 0;
             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.Entity;
 using Microsoft.AspNetCore.Mvc;
-using Microsoft.Net.Http.Headers;
 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Linq.Expressions;
-using System.Text.RegularExpressions;
 
 namespace Masuit.MyBlogs.Core.Controllers
 {
@@ -42,11 +40,6 @@ namespace Masuit.MyBlogs.Core.Controllers
             ViewBag.Total = 0;
             ViewBag.PageSize = size;
             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 key = "Search:" + ip;
             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.Models;
 using Microsoft.AspNetCore.Mvc;
-using Microsoft.Net.Http.Headers;
 using Newtonsoft.Json;
 using System;
 using System.Net.Http;
@@ -60,15 +59,14 @@ namespace Masuit.MyBlogs.Core.Controllers
                 PhysicsAddress address = await ip.GetPhysicsAddressInfo();
                 return View(address);
             }
-            using (HttpClient client = new HttpClient()
+
+            using var client = new HttpClient()
             {
                 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>
@@ -86,7 +84,7 @@ namespace Masuit.MyBlogs.Core.Controllers
                 Random r = new Random();
                 ip = $"{r.Next(210)}.{r.Next(255)}.{r.Next(255)}.{r.Next(255)}";
 #endif
-                PhysicsAddress address = await ip.GetPhysicsAddressInfo();
+                var address = await ip.GetPhysicsAddressInfo();
                 if (address?.Status == 0)
                 {
                     ViewBag.Address = address.AddressResult.FormattedAddress;
@@ -98,26 +96,24 @@ namespace Masuit.MyBlogs.Core.Controllers
                 }
             }
             ViewBag.Address = addr;
-            using (HttpClient client = new HttpClient()
+            using HttpClient client = new HttpClient()
             {
                 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 ext = Path.GetExtension(fileName);
             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", "");
             DocumentConvert.Doc2Html(docPath, htmlDir);
             string htmlfile = Path.Combine(htmlDir, "index.html");
@@ -248,7 +246,7 @@ namespace Masuit.MyBlogs.Core.Controllers
                         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);
                     }
@@ -272,7 +270,7 @@ namespace Masuit.MyBlogs.Core.Controllers
                     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);
                 }

+ 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.Tools.Core.Net;
 using Masuit.Tools.Security;
+using Microsoft.AspNetCore.Http;
 using Microsoft.AspNetCore.Mvc;
 using Microsoft.AspNetCore.Mvc.Filters;
 using Microsoft.Net.Http.Headers;
 using System;
 using System.Linq;
+using System.Text;
 using System.Web;
 
 namespace Masuit.MyBlogs.Core.Extensions
@@ -41,14 +43,7 @@ namespace Masuit.MyBlogs.Core.Extensions
             var ip = context.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
             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;
             }
 
@@ -68,10 +63,11 @@ namespace Masuit.MyBlogs.Core.Extensions
             if (times > limit * 1.2)
             {
                 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()
                 {
                     IP = ip,
-                    RequestUrl = HttpUtility.UrlDecode(request.Scheme + "://" + request.Host + request.Path),
+                    RequestUrl = HttpUtility.UrlDecode(request.Scheme + "://" + request.Host + path),
                     Time = DateTime.Now,
                     UserAgent = request.Headers[HeaderNames.UserAgent]
                 }));
@@ -79,5 +75,18 @@ namespace Masuit.MyBlogs.Core.Extensions
 
             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
             {
-                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);
         }

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

@@ -54,20 +54,11 @@ namespace Masuit.MyBlogs.Core.Extensions
         /// <returns></returns>
         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.DateTimeZoneHandling = DateTimeZoneHandling.Utc; // 设置时区为 UTC
             }).AddControllersAsServices().AddViewComponentsAsServices().AddTagHelpersAsServices(); // MVC
-            services.AddRazorPages().AddViewComponentsAsServices().AddTagHelpersAsServices(); // RazorPage
-
             services.Configure<WebEncoderOptions>(options =>
             {
                 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.Tools;
 using Masuit.Tools.Core.Net;
@@ -6,7 +7,9 @@ using Microsoft.AspNetCore.Http;
 using Microsoft.Net.Http.Headers;
 using System;
 using System.Text;
+using System.Text.RegularExpressions;
 using System.Threading.Tasks;
+using System.Web;
 
 namespace Masuit.MyBlogs.Core.Extensions
 {
@@ -28,6 +31,22 @@ namespace Masuit.MyBlogs.Core.Extensions
 
         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())
             {
                 context.Session.Set("session", 0);
@@ -45,6 +64,7 @@ namespace Masuit.MyBlogs.Core.Extensions
                     }
                     catch
                     {
+                        context.Response.StatusCode = 504;
                         await context.Response.WriteAsync("您的浏览器不支持访问本站!", Encoding.UTF8);
                         return;
                     }

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

@@ -73,26 +73,23 @@ namespace Masuit.MyBlogs.Core.Extensions.UEditor
 
             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";

+ 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);
 
             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;
                 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)))
                 {
-                    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

+ 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.Entity;
+using System.Threading.Tasks;
 
 namespace Masuit.MyBlogs.Core.Infrastructure.Services.Interface
 {
     public partial interface IPostService : IBaseService<Post>
     {
         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>
         /// <returns>受影响的行数</returns>
-        public override int SaveChanges()
+        public int SaveChanges(bool flushIndex)
         {
-            return _searchEngine.SaveChanges();
+            return flushIndex ? _searchEngine.SaveChanges() : base.SaveChanges();
         }
 
         /// <summary>
         /// 统一保存数据
         /// </summary>
         /// <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="CacheManager.Microsoft.Extensions.Caching.Memory" 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="Hangfire" Version="1.7.6" />
     <PackageReference Include="Hangfire.Autofac" Version="2.3.1" />
@@ -63,6 +63,7 @@
     <PackageReference Include="htmldiff.net-core" Version="1.3.6" />
     <PackageReference Include="IP2Region" Version="1.2.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="PanGu.HighLight" Version="1.0.0" />
     <PackageReference Include="Polly" Version="7.1.1" />

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

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

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

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

Энэ ялгаанд хэт олон файл өөрчлөгдсөн тул зарим файлыг харуулаагүй болно