Browse Source

文章页优化

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

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

@@ -14,6 +14,7 @@ using Microsoft.AspNetCore.Mvc;
 using Microsoft.EntityFrameworkCore;
 using Microsoft.Net.Http.Headers;
 using System;
+using System.Linq;
 using System.Web;
 
 namespace Masuit.MyBlogs.Core.Controllers
@@ -58,16 +59,16 @@ namespace Masuit.MyBlogs.Core.Controllers
                 switch (feature.Error)
                 {
                     case DbUpdateConcurrencyException ex:
-                        err = $"异常源:{ex.Source},异常类型:{ex.GetType().Name},\n请求路径:{req.Scheme}://{req.Host}{HttpUtility.UrlDecode(feature.Path)},客户端用户代理:{req.Headers[HeaderNames.UserAgent]},客户端IP:{ip}\t{ex.InnerException?.Message}\t";
+                        err = $"数据库并发更新异常,更新表:{ex.Entries.Select(e => e.Metadata.Name)},\n请求路径:{req.Scheme}://{req.Host}{HttpUtility.UrlDecode(feature.Path)},客户端用户代理:{req.Headers[HeaderNames.UserAgent]},客户端IP:{ip}\t{ex.InnerException?.Message}\t";
                         LogManager.Error(err, ex);
                         break;
                     case DbUpdateException ex:
-                        err = $"异常源:{ex.Source},异常类型:{ex.GetType().Name},\n请求路径:{req.Scheme}://{req.Host}{HttpUtility.UrlDecode(feature.Path)},客户端用户代理:{req.Headers[HeaderNames.UserAgent]},客户端IP:{ip}\t{ex.InnerException?.Message}\t";
+                        err = $"数据库更新时异常,更新表:{ex.Entries.Select(e => e.Metadata.Name)},\n请求路径:{req.Scheme}://{req.Host}{HttpUtility.UrlDecode(feature.Path)},客户端用户代理:{req.Headers[HeaderNames.UserAgent]},客户端IP:{ip}\t{ex.InnerException?.Message}\t";
                         LogManager.Error(err, ex);
                         break;
                     case AggregateException ex:
                         LogManager.Debug("↓↓↓" + ex.Message + "↓↓↓");
-                        ex.Handle(e =>
+                        ex.Flatten().Handle(e =>
                         {
                             LogManager.Error($"异常源:{e.Source},异常类型:{e.GetType().Name},\n请求路径:{req.Scheme}://{req.Host}{HttpUtility.UrlDecode(feature.Path)},客户端用户代理:{req.Headers[HeaderNames.UserAgent]},客户端IP:{ip}\t", e);
                             return true;

+ 4 - 10
src/Masuit.MyBlogs.Core/Controllers/NoticeController.cs

@@ -5,13 +5,11 @@ using Masuit.MyBlogs.Core.Models;
 using Masuit.MyBlogs.Core.Models.DTO;
 using Masuit.MyBlogs.Core.Models.Entity;
 using Masuit.MyBlogs.Core.Models.Enum;
-using Masuit.Tools;
 using Masuit.Tools.Core.Net;
 using Masuit.Tools.Html;
 using Microsoft.AspNetCore.Hosting;
 using Microsoft.AspNetCore.Http;
 using Microsoft.AspNetCore.Mvc;
-using Newtonsoft.Json;
 using System;
 using System.ComponentModel.DataAnnotations;
 using System.Linq;
@@ -156,21 +154,17 @@ namespace Masuit.MyBlogs.Core.Controllers
                 return ResultData(null, false);
             }
 
-            if (Request.Cookies.TryGetValue("last-notice", out var json))
+            if (Request.Cookies.TryGetValue("last-notice", out var id) && notice.Id.ToString() == id)
             {
-                var data = JsonConvert.DeserializeObject<NoticeDto>(json);
-                if (notice.Id == data.Id)
-                {
-                    return ResultData(data);
-                }
+                return ResultData(null, false);
             }
 
             notice.ViewCount += 1;
             NoticeService.SaveChanges();
             var dto = notice.Mapper<NoticeDto>();
-            Response.Cookies.Append("last-notice", dto.ToJsonString(), new CookieOptions()
+            Response.Cookies.Append("last-notice", dto.Id.ToString(), new CookieOptions()
             {
-                Expires = DateTime.Now.AddMonths(1)
+                Expires = DateTime.Now.AddYears(1)
             });
             return ResultData(dto);
         }

+ 28 - 0
src/Masuit.MyBlogs.Core/Infrastructure/DataContext.cs

@@ -2,6 +2,7 @@
 using Masuit.MyBlogs.Core.Models.Entity;
 using Microsoft.EntityFrameworkCore;
 using Microsoft.EntityFrameworkCore.Design;
+using System.Linq;
 
 namespace Masuit.MyBlogs.Core.Infrastructure
 {
@@ -47,6 +48,33 @@ namespace Masuit.MyBlogs.Core.Infrastructure
             modelBuilder.Entity<SeminarPostHistoryVersion>().Property(s => s.PostHistoryVersionId).HasColumnName("PostHistoryVersion_Id");
         }
 
+        public override int SaveChanges()
+        {
+            DbUpdateConcurrencyException ex = null;
+            for (int i = 0; i < 5; i++)
+            {
+                try
+                {
+                    return base.SaveChanges();
+                }
+                catch (DbUpdateConcurrencyException e)
+                {
+                    ex = e;
+                    var entry = e.Entries.Single();
+                    var databaseValues = entry.GetDatabaseValues();
+                    var resolvedValues = databaseValues.Clone();
+                    entry.OriginalValues.SetValues(databaseValues);
+                    entry.CurrentValues.SetValues(resolvedValues);
+                }
+                catch
+                {
+                    throw;
+                }
+            }
+
+            throw ex;
+        }
+
         public virtual DbSet<Broadcast> Broadcast { get; set; }
         public virtual DbSet<Category> Category { get; set; }
         public virtual DbSet<Comment> Comment { get; set; }

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

@@ -30,7 +30,7 @@
         <PackageReference Include="CacheManager.Serialization.Json" Version="2.0.0-beta-1629" />
         <PackageReference Include="CSRedisCore" Version="3.6.1" />
         <PackageReference Include="DocxToHtml_ldqk" Version="1.0.4" />
-        <PackageReference Include="EFCoreSecondLevelCacheInterceptor" Version="1.5.1" />
+        <PackageReference Include="EFCoreSecondLevelCacheInterceptor" Version="1.5.2" />
         <PackageReference Include="Hangfire" Version="1.7.10" />
         <PackageReference Include="Hangfire.Autofac" Version="2.3.1" />
         <PackageReference Include="Hangfire.MemoryStorage" Version="1.7.0" />

+ 1 - 0
src/Masuit.MyBlogs.Core/Models/Entity/Notice.cs

@@ -44,6 +44,7 @@ namespace Masuit.MyBlogs.Core.Models.Entity
         /// <summary>
         /// ä¯ÀÀÈËÊý
         /// </summary>
+        [ConcurrencyCheck]
         public int ViewCount { get; set; }
     }
 }

+ 3 - 3
src/Masuit.MyBlogs.Core/Startup.cs

@@ -98,7 +98,7 @@ namespace Masuit.MyBlogs.Core
                 opt.UseMySql(AppConfig.ConnString, builder => builder.EnableRetryOnFailure(3)).EnableDetailedErrors().EnableSensitiveDataLogging();
                 //opt.UseSqlServer(AppConfig.ConnString);
             }); //配置数据库
-            services.AddCors(opt => opt.AddDefaultPolicy(p => p.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin())); //配置跨域
+            //services.AddCors(opt => opt.AddDefaultPolicy(p => p.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin())); //配置跨域
             services.Configure<FormOptions>(options =>
             {
                 options.MultipartBodyLengthLimit = 104857600; // 100MB
@@ -204,7 +204,7 @@ namespace Masuit.MyBlogs.Core
                     new MyRestrictiveAuthorizationFilter()
                 }
             }); //配置hangfire
-            app.UseCors(builder => builder.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin()); //配置跨域
+            //app.UseCors(builder => builder.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin()); //配置跨域
             app.UseResponseCaching().UseResponseCompression(); //启动Response缓存
             app.UseRouting(); // 放在 UseStaticFiles 之后
             app.UseEndpoints(endpoints =>
@@ -216,7 +216,7 @@ namespace Masuit.MyBlogs.Core
             HangfireJobInit.Start(); //初始化定时任务
         }
 
-        private static void UseLuceneSearch(IWebHostEnvironment env, IHangfireBackJob hangfire, LuceneIndexerOptions luceneIndexerOptions)
+        private static void UseLuceneSearch(IHostEnvironment env, IHangfireBackJob hangfire, LuceneIndexerOptions luceneIndexerOptions)
         {
             Task.Run(() =>
             {

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

@@ -61,19 +61,19 @@
                                 @{
                                     if (!string.IsNullOrEmpty(Model.Label))
                                     {
-                                        <div class="pull-right margin-right20">
-                                            <div>
-                                                @foreach (string s in Model.Label.Split(',', ','))
+                                    <div class="pull-right margin-right20">
+                                        <div>
+                                            @foreach (string s in Model.Label.Split(',', ','))
                                                 {
                                                     if (!string.IsNullOrEmpty(s))
                                                     {
-                                                        <a asp-controller="Home" asp-action="Tag" asp-route-id="@s">
-                                                            <span class="label label-@colors[new Random().Next() % colors.Length]">@s</span>
-                                                        </a>
+                                            <a asp-controller="Home" asp-action="Tag" asp-route-id="@s">
+                                                <span class="label label-@colors[new Random().Next() % colors.Length]">@s</span>
+                                            </a>
                                                     }
                                                 }
-                                            </div>
                                         </div>
+                                    </div>
                                     }
                                 }
                             </div>
@@ -82,12 +82,12 @@
                                     分类:<i class="icon-map-pin"></i><a asp-controller="Home" asp-action="Category" asp-route-id="@Model.CategoryId" class="label label-@colors[new Random().Next() % colors.Length]">@Model.Category.Name</a> | 评论总数:<span class="text-danger">@Model.Comment.Count</span>条 | 热度:<span class="text-danger">@Model.TotalViewCount</span>℃
                                     @if (Model.Seminar.Any())
                                     {
-                                        <span> | 所属专题:</span>
+                                    <span> | 所属专题:</span>
                                         var seminars = Model.Seminar;
                                         foreach (var s in seminars)
                                         {
-                                            <a asp-controller="Seminar" asp-action="Index" asp-route-id="@s.SeminarId" class="label label-@colors[new Random().Next() % colors.Length]">@s.Seminar.Title</a>
-                                            <text> </text>
+                                    <a asp-controller="Seminar" asp-action="Index" asp-route-id="@s.SeminarId" class="label label-@colors[new Random().Next() % colors.Length]">@s.Seminar.Title</a>
+                                    <text> </text>
                                         }
                                     }
                                     <div class="pull-right margin-right20">
@@ -95,6 +95,9 @@
                                     </div>
                                 </div>
                             </div>
+                            @if(DateTime.Now-Model.ModifyDate>TimeSpan.FromDays(365)) {
+                            <p class="text-focus text-center">该文章已经超过1年未更新,可能无法为您提供及时准确的资讯,请根据当下实际情况,酌情参考本文内容。</p>
+                            }
                         </header>
                         <article class="article" id="article">
                             @Html.Raw(Model.Content.ReplaceImgAttribute(Model.Title))

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

@@ -63,19 +63,19 @@
                                 @{
                                     if (!string.IsNullOrEmpty(Model.Label))
                                     {
-                                        <div class="pull-right margin-right20">
-                                            <div>
-                                                @foreach (string s in Model.Label.Split(',', ','))
+                                    <div class="pull-right margin-right20">
+                                        <div>
+                                            @foreach (string s in Model.Label.Split(',', ','))
                                                 {
                                                     if (!string.IsNullOrEmpty(s))
                                                     {
-                                                        <a asp-controller="Home" asp-action="Tag" asp-route-id="@s">
-                                                            <span class="label label-@colors[new Random().Next() % colors.Length]">@s</span>
-                                                        </a>
+                                            <a asp-controller="Home" asp-action="Tag" asp-route-id="@s">
+                                                <span class="label label-@colors[new Random().Next() % colors.Length]">@s</span>
+                                            </a>
                                                     }
                                                 }
-                                            </div>
                                         </div>
+                                    </div>
                                     }
                                 }
                             </div>
@@ -84,11 +84,11 @@
                                     分类:<i class="icon-map-pin"></i><a asp-controller="Home" asp-action="Category" asp-route-id="@Model.CategoryId" class="label label-@colors[new Random().Next() % colors.Length]">@Model.Category.Name</a>  | 评论总数:<span class="text-danger">@Model.Comment.Count</span>条 | 热度:<span class="text-danger">@Model.TotalViewCount</span>℃ | 状态:@Model.Status.GetDisplay()
                                     @if (Model.Seminar.Any())
                                     {
-                                        <span> | 所属专题:</span>
+                                    <span> | 所属专题:</span>
                                         var seminars = Model.Seminar;
                                         foreach (var s in seminars)
                                         {
-                                            <a asp-controller="Seminar" asp-action="Index" asp-route-id="@s.SeminarId" class="label label-@colors[new Random().Next() % colors.Length]">@s.Seminar.Title</a><text> </text>
+                                    <a asp-controller="Seminar" asp-action="Index" asp-route-id="@s.SeminarId" class="label label-@colors[new Random().Next() % colors.Length]">@s.Seminar.Title</a><text> </text>
                                         }
                                     }
                                     <div class="pull-right margin-right20">
@@ -96,15 +96,15 @@
                                             <a asp-controller="Post" asp-action="Refresh" asp-route-id="@Model.Id" class="btn btn-info">刷新</a>
                                             @if (Model.IsFixedTop)
                                             {
-                                                <button class="btn btn-success" id="pin">取消置顶</button>
+                                            <button class="btn btn-success" id="pin">取消置顶</button>
                                             }
                                             else
                                             {
-                                                <button class="btn btn-success" id="pin">置顶</button>
+                                            <button class="btn btn-success" id="pin">置顶</button>
                                             }
                                             @if (Model.Status == Status.Pending)
                                             {
-                                                <button class="btn btn-primary" id="pass">通过</button>
+                                            <button class="btn btn-primary" id="pass">通过</button>
                                             }
                                             <a asp-controller="Dashboard" asp-action="Index" asp-fragment="/post/[email protected]" class="btn btn-primary" target="_blank">修改</a>
                                             <button class="btn btn-danger" id="del">删除</button>
@@ -112,6 +112,9 @@
                                     </div>
                                 </div>
                             </div>
+                            @if(DateTime.Now-Model.ModifyDate>TimeSpan.FromDays(365)) {
+                            <p class="text-focus text-center">该文章已经超过1年未更新,可能无法为您提供及时准确的资讯,请根据当下实际情况,酌情参考本文内容。</p>
+                            }
                         </header>
                         <article class="article" id="article">
                             @Html.Raw(Model.Content)