Browse Source

模版引擎

懒得勤快 5 years ago
parent
commit
c70912ef79

+ 15 - 14
src/Masuit.MyBlogs.Core/Controllers/CommentController.cs

@@ -10,6 +10,7 @@ using Masuit.MyBlogs.Core.Models.ViewModel;
 using Masuit.Tools;
 using Masuit.Tools.Core.Net;
 using Masuit.Tools.Html;
+using Masuit.Tools.Strings;
 using Microsoft.AspNetCore.Hosting;
 using Microsoft.AspNetCore.Http;
 using Microsoft.AspNetCore.Mvc;
@@ -93,11 +94,11 @@ namespace Masuit.MyBlogs.Core.Controllers
             var emails = new HashSet<string>();
             var email = CommonHelper.SystemSettings["ReceiveEmail"]; //站长邮箱
             emails.Add(email);
-            var content = (await System.IO.File.ReadAllTextAsync(HostEnvironment.WebRootPath + "/template/notify.html"))
-                .Replace("{{title}}", post.Title)
-                .Replace("{{time}}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))
-                .Replace("{{nickname}}", comment.NickName)
-                .Replace("{{content}}", comment.Content);
+            var content = new Template(await System.IO.File.ReadAllTextAsync(HostEnvironment.WebRootPath + "/template/notify.html"))
+                .Set("title", post.Title)
+                .Set("time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))
+                .Set("nickname", comment.NickName)
+                .Set("content", comment.Content);
             if (comment.Status == Status.Published)
             {
                 if (!comment.IsMaster)
@@ -117,7 +118,7 @@ namespace Masuit.MyBlogs.Core.Controllers
                     //新评论,只通知博主和楼主
                     foreach (var s in emails)
                     {
-                        BackgroundJob.Enqueue(() => CommonHelper.SendMail(Request.Host + "|博客文章新评论:", content.Replace("{{link}}", Url.Action("Details", "Post", new { id = comment.PostId, cid = comment.Id }, Request.Scheme) + "#comment"), s));
+                        BackgroundJob.Enqueue(() => CommonHelper.SendMail(Request.Host + "|博客文章新评论:", content.Set("link", Url.Action("Details", "Post", new { id = comment.PostId, cid = comment.Id }, Request.Scheme) + "#comment").Render(), s));
                     }
                 }
                 else
@@ -130,7 +131,7 @@ namespace Masuit.MyBlogs.Core.Controllers
                     string link = Url.Action("Details", "Post", new { id = comment.PostId, cid = comment.Id }, Request.Scheme) + "#comment";
                     foreach (var s in emails)
                     {
-                        BackgroundJob.Enqueue(() => CommonHelper.SendMail($"{Request.Host}{CommonHelper.SystemSettings["Title"]}文章评论回复:", content.Replace("{{link}}", link), s));
+                        BackgroundJob.Enqueue(() => CommonHelper.SendMail($"{Request.Host}{CommonHelper.SystemSettings["Title"]}文章评论回复:", content.Set("link", link).Render(), s));
                     }
                 }
 #endif
@@ -139,7 +140,7 @@ namespace Masuit.MyBlogs.Core.Controllers
 
             foreach (var s in emails)
             {
-                BackgroundJob.Enqueue(() => CommonHelper.SendMail(Request.Host + "|博客文章新评论(待审核):", content.Replace("{{link}}", Url.Action("Details", "Post", new { id = comment.PostId, cid = comment.Id }, Request.Scheme) + "#comment") + "<p style='color:red;'>(待审核)</p>", s));
+                BackgroundJob.Enqueue(() => CommonHelper.SendMail(Request.Host + "|博客文章新评论(待审核):", content.Set("link", Url.Action("Details", "Post", new { id = comment.PostId, cid = comment.Id }, Request.Scheme) + "#comment").Render() + "<p style='color:red;'>(待审核)</p>", s));
             }
 
             return ResultData(null, true, "评论成功,待站长审核通过以后将显示");
@@ -234,11 +235,11 @@ namespace Masuit.MyBlogs.Core.Controllers
             {
                 var pid = comment.ParentId == 0 ? comment.Id : CommentService.GetParentCommentIdByChildId(id);
 #if !DEBUG
-                var content = (await System.IO.File.ReadAllTextAsync(Path.Combine(HostEnvironment.WebRootPath, "template", "notify.html")))
-                    .Replace("{{title}}", post.Title)
-                    .Replace("{{time}}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))
-                    .Replace("{{nickname}}", comment.NickName)
-                    .Replace("{{content}}", comment.Content);
+                var content = new Template(await System.IO.File.ReadAllTextAsync(Path.Combine(HostEnvironment.WebRootPath, "template", "notify.html")))
+                    .Set("title", post.Title)
+                    .Set("time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))
+                    .Set("nickname", comment.NickName)
+                    .Set("content", comment.Content);
                 var emails = CommentService.GetSelfAndAllChildrenCommentsByParentId(pid).Select(c => c.Email).Append(post.ModifierEmail).Except(new List<string> { comment.Email, CurrentUser.Email }).ToHashSet();
                 var link = Url.Action("Details", "Post", new
                 {
@@ -247,7 +248,7 @@ namespace Masuit.MyBlogs.Core.Controllers
                 }, Request.Scheme) + "#comment";
                 foreach (var email in emails)
                 {
-                    BackgroundJob.Enqueue(() => CommonHelper.SendMail($"{Request.Host}{CommonHelper.SystemSettings["Title"]}文章评论回复:", content.Replace("{{link}}", link), email));
+                    BackgroundJob.Enqueue(() => CommonHelper.SendMail($"{Request.Host}{CommonHelper.SystemSettings["Title"]}文章评论回复:", content.Set("link", link).Render(), email));
                 }
 #endif
                 return ResultData(null, true, "审核通过!");

+ 20 - 1
src/Masuit.MyBlogs.Core/Controllers/ErrorController.cs

@@ -6,11 +6,13 @@ using Masuit.MyBlogs.Core.Infrastructure.Services.Interface;
 using Masuit.Tools;
 using Masuit.Tools.Logging;
 using Masuit.Tools.Security;
+using Masuit.Tools.Strings;
 using Masuit.Tools.Systems;
 using Microsoft.AspNetCore.Diagnostics;
 using Microsoft.AspNetCore.Http;
 using Microsoft.AspNetCore.Mvc;
 using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Internal;
 using Microsoft.Net.Http.Headers;
 using System;
 using System.Linq;
@@ -56,6 +58,12 @@ namespace Masuit.MyBlogs.Core.Controllers
                 string err;
                 var req = HttpContext.Request;
                 var ip = HttpContext.Connection.RemoteIpAddress.ToString();
+                var trueip = Request.Headers[AppConfig.TrueClientIPHeader].ToString();
+                if (!string.IsNullOrEmpty(trueip) && ip != trueip)
+                {
+                    ip = trueip;
+                }
+
                 switch (feature.Error)
                 {
                     case DbUpdateConcurrencyException ex:
@@ -83,8 +91,19 @@ namespace Masuit.MyBlogs.Core.Controllers
                             ex.Message
                         });
                     case AccessDenyException _:
+                        var parts = ip.GetIPLocation().Split('|');
+                        var network = "未知";
+                        var location = parts.Join("");
+                        if (parts.Length > 2)
+                        {
+                            network = parts[^1];
+                            location = parts[..^1].Join("");
+                        }
+
+                        var tips = new Template(CommonHelper.SystemSettings.GetOrAdd("AccessDenyTips", @"<h4>遇到了什么问题?</h4>
+                <h4>基于主观因素考虑,您所在的地区暂时不允许访问本站,如有疑问,请联系站长!或者请联系站长开通本站的访问权限!</h4>")).Set("clientip", ip).Set(nameof(location), location).Set(nameof(network), network).Render();
                         Response.StatusCode = 403;
-                        return View("AccessDeny");
+                        return View("AccessDeny", tips);
                     case TempDenyException _:
                         Response.StatusCode = 403;
                         return View("TempDeny");

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

@@ -9,6 +9,7 @@ using Masuit.MyBlogs.Core.Models.Command;
 using Masuit.MyBlogs.Core.Models.DTO;
 using Masuit.MyBlogs.Core.Models.Entity;
 using Masuit.MyBlogs.Core.Models.Enum;
+using Masuit.Tools.Strings;
 using Microsoft.AspNetCore.Hosting;
 using Microsoft.AspNetCore.Mvc;
 using System;
@@ -95,7 +96,7 @@ namespace Masuit.MyBlogs.Core.Controllers
             }
 
             string link = Request.Scheme + "://" + Request.Host + "/" + merge.Post.Id;
-            string content = System.IO.File.ReadAllText(HostEnvironment.WebRootPath + "/template/merge-pass.html").Replace("{{link}}", link).Replace("{{title}}", merge.Post.Title);
+            string content = new Template(System.IO.File.ReadAllText(HostEnvironment.WebRootPath + "/template/merge-pass.html")).Set("link", link).Set("title", merge.Post.Title).Render();
             BackgroundJob.Enqueue(() => CommonHelper.SendMail(CommonHelper.SystemSettings["Title"] + "博客你提交的修改已通过", content, merge.ModifierEmail));
             return ResultData(null, true, "文章合并完成!");
 
@@ -107,7 +108,7 @@ namespace Masuit.MyBlogs.Core.Controllers
         /// <param name="dto"></param>
         /// <returns></returns>
         [HttpPost]
-        public IActionResult Merge([FromForm]PostMergeRequestCommandBase dto)
+        public IActionResult Merge([FromForm] PostMergeRequestCommandBase dto)
         {
             var merge = PostMergeRequestService.GetById(dto.Id) ?? throw new NotFoundException("待合并文章未找到");
             Mapper.Map(dto, merge);
@@ -133,7 +134,7 @@ namespace Masuit.MyBlogs.Core.Controllers
             }
 
             var link = Request.Scheme + "://" + Request.Host + "/" + merge.Post.Id + "/merge/" + id;
-            var content = System.IO.File.ReadAllText(HostEnvironment.WebRootPath + "/template/merge-reject.html").Replace("{{link}}", link).Replace("{{title}}", merge.Post.Title).Replace("{{reason}}", reason);
+            var content = new Template(System.IO.File.ReadAllText(HostEnvironment.WebRootPath + "/template/merge-reject.html")).Set("link", link).Set("title", merge.Post.Title).Set("reason", reason).Render();
             BackgroundJob.Enqueue(() => CommonHelper.SendMail(CommonHelper.SystemSettings["Title"] + "博客你提交的修改已被拒绝", content, merge.ModifierEmail));
             return ResultData(null, true, "合并已拒绝!");
         }

+ 8 - 7
src/Masuit.MyBlogs.Core/Controllers/MsgController.cs

@@ -10,6 +10,7 @@ using Masuit.MyBlogs.Core.Models.ViewModel;
 using Masuit.Tools;
 using Masuit.Tools.Core.Net;
 using Masuit.Tools.Html;
+using Masuit.Tools.Strings;
 using Microsoft.AspNetCore.Hosting;
 using Microsoft.AspNetCore.Mvc;
 using Microsoft.EntityFrameworkCore.Internal;
@@ -151,7 +152,7 @@ namespace Masuit.MyBlogs.Core.Controllers
 
             HttpContext.Session.Set("msg", msg.Content.RemoveHtmlTag().Trim());
             var email = CommonHelper.SystemSettings["ReceiveEmail"];
-            var content = System.IO.File.ReadAllText(HostEnvironment.WebRootPath + "/template/notify.html").Replace("{{title}}", "网站留言板").Replace("{{time}}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")).Replace("{{nickname}}", msg.NickName).Replace("{{content}}", msg.Content);
+            var content = new Template(System.IO.File.ReadAllText(HostEnvironment.WebRootPath + "/template/notify.html")).Set("title", "网站留言板").Set("time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")).Set("nickname", msg.NickName).Set("content", msg.Content);
             if (msg.Status == Status.Published)
             {
                 if (!msg.IsMaster)
@@ -167,7 +168,7 @@ namespace Masuit.MyBlogs.Core.Controllers
                 if (msg.ParentId == 0)
                 {
                     //新评论,只通知博主
-                    BackgroundJob.Enqueue(() => CommonHelper.SendMail(Request.Host + "|博客新留言:", content.Replace("{{link}}", Url.Action("Index", "Msg", new { cid = msg.Id }, Request.Scheme)), email));
+                    BackgroundJob.Enqueue(() => CommonHelper.SendMail(Request.Host + "|博客新留言:", content.Set("link", Url.Action("Index", "Msg", new { cid = msg.Id }, Request.Scheme)).Render(), email));
                 }
                 else
                 {
@@ -177,17 +178,17 @@ namespace Masuit.MyBlogs.Core.Controllers
                     string link = Url.Action("Index", "Msg", new { cid = msg.Id }, Request.Scheme);
                     foreach (var s in emails)
                     {
-                        BackgroundJob.Enqueue(() => CommonHelper.SendMail($"{Request.Host}{CommonHelper.SystemSettings["Title"]} 留言回复:", content.Replace("{{link}}", link), s));
+                        BackgroundJob.Enqueue(() => CommonHelper.SendMail($"{Request.Host}{CommonHelper.SystemSettings["Title"]} 留言回复:", content.Set("link", link).Render(), s));
                     }
                 }
 #endif
                 return ResultData(null, true, "留言发表成功,服务器正在后台处理中,这会有一定的延迟,稍后将会显示到列表中!");
             }
 
-            BackgroundJob.Enqueue(() => CommonHelper.SendMail(Request.Host + "|博客新留言(待审核):", content.Replace("{{link}}", Url.Action("Index", "Msg", new
+            BackgroundJob.Enqueue(() => CommonHelper.SendMail(Request.Host + "|博客新留言(待审核):", content.Set("link", Url.Action("Index", "Msg", new
             {
                 cid = msg.Id
-            }, Request.Scheme)) + "<p style='color:red;'>(待审核)</p>", email));
+            }, Request.Scheme)).Render() + "<p style='color:red;'>(待审核)</p>", email));
             return ResultData(null, true, "留言发表成功,待站长审核通过以后将显示到列表中!");
         }
 
@@ -204,12 +205,12 @@ namespace Masuit.MyBlogs.Core.Controllers
             bool b = LeaveMessageService.SaveChanges() > 0;
 #if !DEBUG
             var pid = msg.ParentId == 0 ? msg.Id : LeaveMessageService.GetParentMessageIdByChildId(id);
-            var content = System.IO.File.ReadAllText(Path.Combine(HostEnvironment.WebRootPath, "template", "notify.html")).Replace("{{time}}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")).Replace("{{nickname}}", msg.NickName).Replace("{{content}}", msg.Content);
+            var content = new Template(System.IO.File.ReadAllText(Path.Combine(HostEnvironment.WebRootPath, "template", "notify.html"))).Set("time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")).Set("nickname", msg.NickName).Set("content", msg.Content);
             var emails = LeaveMessageService.GetSelfAndAllChildrenMessagesByParentId(pid).Select(c => c.Email).Except(new List<string> { msg.Email, CurrentUser.Email }).ToHashSet();
             var link = Url.Action("Index", "Msg", new { cid = pid }, Request.Scheme);
             foreach (var s in emails)
             {
-                BackgroundJob.Enqueue(() => CommonHelper.SendMail($"{Request.Host}{CommonHelper.SystemSettings["Title"]} 留言回复:", content.Replace("{{link}}", link), s));
+                BackgroundJob.Enqueue(() => CommonHelper.SendMail($"{Request.Host}{CommonHelper.SystemSettings["Title"]} 留言回复:", content.Set("link", link).Render(), s));
             }
 #endif
             return ResultData(null, b, b ? "审核通过!" : "审核失败!");

+ 6 - 5
src/Masuit.MyBlogs.Core/Controllers/PostController.cs

@@ -18,6 +18,7 @@ using Masuit.Tools;
 using Masuit.Tools.Core.Net;
 using Masuit.Tools.Html;
 using Masuit.Tools.Security;
+using Masuit.Tools.Strings;
 using Masuit.Tools.Systems;
 using Microsoft.AspNetCore.Hosting;
 using Microsoft.AspNetCore.Http;
@@ -241,10 +242,10 @@ namespace Masuit.MyBlogs.Core.Controllers
             }
 
             await RedisHelper.ExpireAsync("code:" + p.Email, 1);
-            var content = (await System.IO.File.ReadAllTextAsync(HostEnvironment.WebRootPath + "/template/publish.html"))
-                .Replace("{{link}}", Url.Action("Details", "Post", new { id = p.Id }, Request.Scheme))
-                .Replace("{{time}}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))
-                .Replace("{{title}}", p.Title);
+            var content = new Template(await System.IO.File.ReadAllTextAsync(HostEnvironment.WebRootPath + "/template/publish.html"))
+                .Set("link", Url.Action("Details", "Post", new { id = p.Id }, Request.Scheme))
+                .Set("time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))
+                .Set("title", p.Title).Render();
             BackgroundJob.Enqueue(() => CommonHelper.SendMail(CommonHelper.SystemSettings["Title"] + "有访客投稿:", content, CommonHelper.SystemSettings["ReceiveEmail"]));
             return ResultData(p.Mapper<PostDto>(), message: "文章发表成功,待站长审核通过以后将显示到列表中!");
         }
@@ -448,7 +449,7 @@ namespace Masuit.MyBlogs.Core.Controllers
                 Content = dto.Title,
                 Link = "#/merge/compare?id=" + merge.Id
             });
-            var content = System.IO.File.ReadAllText(HostEnvironment.WebRootPath + "/template/merge-request.html").Replace("{{title}}", post.Title).Replace("{{link}}", Url.Action("Index", "Dashboard", new { }, Request.Scheme) + "#/merge/compare?id=" + merge.Id);
+            var content = new Template(System.IO.File.ReadAllText(HostEnvironment.WebRootPath + "/template/merge-request.html")).Set("title", post.Title).Set("link", Url.Action("Index", "Dashboard", new { }, Request.Scheme) + "#/merge/compare?id=" + merge.Id).Render();
             BackgroundJob.Enqueue(() => CommonHelper.SendMail("博客文章修改请求:", content, CommonHelper.SystemSettings["ReceiveEmail"]));
             return ResultData(null, true, "您的修改请求已提交,已进入审核状态,感谢您的参与!");
         }

+ 0 - 3
src/Masuit.MyBlogs.Core/Extensions/FirewallAttribute.cs

@@ -30,9 +30,6 @@ namespace Masuit.MyBlogs.Core.Extensions
             var trueip = request.Headers[AppConfig.TrueClientIPHeader].ToString();
             if (!string.IsNullOrEmpty(trueip) && ip != trueip)
             {
-                //AccessDeny(trueip, request, "客户端请求不合法,伪造IP:" + ip);
-                //context.Result = new BadRequestObjectResult("当前请求已被非法篡改,本站阻止访问!如果你不知道发生了什么,请尝试关闭如adguard隐身模式、代理软件、可能会修改http请求的浏览器扩展等再进行重试!");
-                //return;
                 ip = trueip;
             }
 

+ 6 - 5
src/Masuit.MyBlogs.Core/Extensions/Hangfire/HangfireBackJob.cs

@@ -7,6 +7,7 @@ using Masuit.MyBlogs.Core.Models.Entity;
 using Masuit.MyBlogs.Core.Models.Enum;
 using Masuit.Tools;
 using Masuit.Tools.Core.Net;
+using Masuit.Tools.Strings;
 using Microsoft.AspNetCore.Hosting;
 using System;
 using System.Collections.Generic;
@@ -82,11 +83,11 @@ namespace Masuit.MyBlogs.Core.Extensions.Hangfire
             var u = _userInfoService.GetByUsername(userInfo.Username);
             u.LoginRecord.Add(record);
             _userInfoService.SaveChanges();
-            var content = File.ReadAllText(Path.Combine(_hostEnvironment.WebRootPath, "template", "login.html"))
-                .Replace("{{name}}", u.Username)
-                .Replace("{{time}}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))
-                .Replace("{{ip}}", record.IP)
-                .Replace("{{address}}", record.PhysicAddress);
+            var content = new Template(File.ReadAllText(Path.Combine(_hostEnvironment.WebRootPath, "template", "login.html")))
+                .Set("name", u.Username)
+                .Set("time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))
+                .Set("ip", record.IP)
+                .Set("address", record.PhysicAddress).Render();
             CommonHelper.SendMail(_settingService.Get(s => s.Name.Equals("Title")).Value + "账号登录通知", content, _settingService.Get(s => s.Name.Equals("ReceiveEmail")).Value);
         }
 

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

@@ -24,9 +24,8 @@
     <ItemGroup>
         <PackageReference Include="Aliyun.OSS.SDK.NetCore" Version="2.10.0" />
         <PackageReference Include="Autofac.Extensions.DependencyInjection" Version="6.0.0" />
-        <PackageReference Include="AutoMapper" Version="10.0.0" />
         <PackageReference Include="AutoMapper.Extensions.ExpressionMapping" Version="4.0.0" />
-        <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="7.0.0" />
+        <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="8.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.6.5" />

+ 5 - 10
src/Masuit.MyBlogs.Core/Views/Error/AccessDeny.cshtml

@@ -1,6 +1,9 @@
-@using Masuit.Tools
+@model string
+@using Masuit.Tools
 @using Microsoft.Net.Http.Headers
 @using Masuit.MyBlogs.Core.Common
+@using Masuit.Tools.Strings
+@using Microsoft.EntityFrameworkCore.Internal
 
 @{
     Layout = null;
@@ -59,15 +62,7 @@
                     <span class="STYLE1">Sorry!访问被拒绝&nbsp;</span>
                 </em>
             </h3>
-            @if (string.IsNullOrEmpty(CommonHelper.SystemSettings.GetOrAdd("AccessDenyTips", "")))
-            {
-                <h4>遇到了什么问题?</h4>
-                <h4>基于主观因素考虑,您所在的地区暂时不允许访问本站,如有疑问,请联系站长!或者请联系站长开通本站的访问权限!</h4>
-            }
-            else
-            {
-                @Html.Raw(CommonHelper.SystemSettings["AccessDenyTips"])
-            }
+            @Html.Raw(Model)
             <form action="/" method="post" class="form-inline" id="code-token">
                 @Html.AntiForgeryToken()
                 <div class="input-group">