Skip to content

Commit

Permalink
优化图片懒加载
Browse files Browse the repository at this point in the history
  • Loading branch information
ldqk committed Feb 22, 2022
1 parent 511926a commit f02e5ad
Show file tree
Hide file tree
Showing 10 changed files with 44 additions and 36 deletions.
1 change: 1 addition & 0 deletions src/Masuit.MyBlogs.Core/Common/CommonHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,7 @@ public static async Task<string> ReplaceImgAttribute(this string html, string ti
string src = node.Attributes["src"].Value;
node.RemoveAttribute("src");
node.SetAttribute("data-src", src);
node.SetAttribute("decoding", "async");
node.SetAttribute("class", node.Attributes["class"]?.Value + " lazyload");
node.SetAttribute("loading", "lazy");
node.SetAttribute("alt", SystemSettings["Title"]);
Expand Down
26 changes: 5 additions & 21 deletions src/Masuit.MyBlogs.Core/Controllers/BaseController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,6 @@ public class BaseController : Controller
{
public IUserInfoService UserInfoService { get; set; }

public IMenuService MenuService { get; set; }

public ILinksService LinksService { get; set; }

public IAdvertisementService AdsService { get; set; }
Expand Down Expand Up @@ -104,9 +102,7 @@ protected string ReplaceVariables(string text)
return text;
}

/// <summary>在调用操作方法前调用。</summary>
/// <param name="filterContext">有关当前请求和操作的信息。</param>
public override void OnActionExecuting(ActionExecutingContext filterContext)
public override Task OnActionExecutionAsync(ActionExecutingContext filterContext, ActionExecutionDelegate next)
{
ViewBag.Desc = CommonHelper.SystemSettings["Description"];
var user = filterContext.HttpContext.Session.Get<UserInfoDto>(SessionKey.UserInfo);
Expand All @@ -117,11 +113,13 @@ public override void OnActionExecuting(ActionExecutingContext filterContext)
if (CommonHelper.SystemSettings.GetOrAdd("CloseSite", "false") == "true" && user?.IsAdmin != true)
{
filterContext.Result = RedirectToAction("ComingSoon", "Error");
return Task.CompletedTask;
}

if (Request.Method == HttpMethods.Post && !Request.Path.Value.Contains("get", StringComparison.InvariantCultureIgnoreCase) && CommonHelper.SystemSettings.GetOrAdd("DataReadonly", "false") == "true" && !filterContext.Filters.Any(m => m.ToString().Contains(nameof(MyAuthorizeAttribute))))
{
filterContext.Result = ResultData("网站当前处于数据写保护状态,无法提交任何数据,如有疑问请联系网站管理员!", false, "网站当前处于数据写保护状态,无法提交任何数据,如有疑问请联系网站管理员!", user != null, HttpStatusCode.BadRequest);
return Task.CompletedTask;
}

if (user == null && Request.Cookies.ContainsKey("username") && Request.Cookies.ContainsKey("password")) //执行自动登录
Expand All @@ -145,28 +143,14 @@ public override void OnActionExecuting(ActionExecutingContext filterContext)
}
}

if (ModelState.IsValid) return;
if (ModelState.IsValid) return next();
var errmsgs = ModelState.SelectMany(kv => kv.Value.Errors.Select(e => e.ErrorMessage)).Select((s, i) => $"{i + 1}. {s}").ToList();
filterContext.Result = true switch
{
_ when Request.HasJsonContentType() || Request.Method == HttpMethods.Post => ResultData(errmsgs, false, "数据校验失败,错误信息:" + errmsgs.Join(" | "), user != null, HttpStatusCode.BadRequest),
_ => base.BadRequest("参数错误:" + errmsgs.Join(" | "))
};
}

/// <summary>在调用操作方法后调用。</summary>
/// <param name="filterContext">有关当前请求和操作的信息。</param>
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
if (filterContext.Result is ViewResult)
{
ViewBag.menus = MenuService.GetQueryFromCache(m => m.ParentId == null && m.Status == Status.Available).OrderBy(m => m.Sort).ToList(); //菜单
var model = new PageFootViewModel //页脚
{
Links = LinksService.GetQuery(l => l.Status == Status.Available).OrderByDescending(l => l.Recommend).ThenByDescending(l => l.Loopbacks.Count).Take(30).ProjectTo<LinksDto>(MapperConfig).Cacheable().ToList()
};
ViewBag.Footer = model;
}
return Task.CompletedTask;
}

/// <summary>
Expand Down
16 changes: 14 additions & 2 deletions src/Masuit.MyBlogs.Core/Controllers/Drive/DriveController.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
using Masuit.MyBlogs.Core.Extensions.Firewall;
using Masuit.MyBlogs.Core.Common;
using Masuit.MyBlogs.Core.Extensions.Firewall;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace Masuit.MyBlogs.Core.Controllers.Drive
{
Expand All @@ -11,5 +13,15 @@ public IActionResult Index()
{
return View();
}

public override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
if (CommonHelper.SystemSettings.GetOrAdd("CloseSite", "false") == "true")
{
context.Result = RedirectToAction("ComingSoon", "Error");
return Task.CompletedTask;
}
return next();
}
}
}
}
14 changes: 11 additions & 3 deletions src/Masuit.MyBlogs.Core/Controllers/Drive/SitesController.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using Masuit.MyBlogs.Core.Common;
using Masuit.MyBlogs.Core.Extensions.DriveHelpers;
using Masuit.MyBlogs.Core.Extensions.Firewall;
using Masuit.MyBlogs.Core.Infrastructure.Drive;
Expand All @@ -6,6 +7,7 @@
using Masuit.MyBlogs.Core.Models.ViewModel;
using Masuit.Tools.Core.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

Expand All @@ -29,8 +31,6 @@ public SitesController(IDriveAccountService siteService, IDriveService driveServ
this._setting = setting;
}

#region Actions

/// <summary>
/// 返回所有sites
/// </summary>
Expand Down Expand Up @@ -250,6 +250,14 @@ public async Task<IActionResult> GetUploadUrl(string siteName, string path, stri
}
}

#endregion Actions
public override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
if (CommonHelper.SystemSettings.GetOrAdd("CloseSite", "false") == "true")
{
context.Result = new BadRequestObjectResult(new { code = 403 });
return Task.CompletedTask;
}
return next();
}
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using Hangfire;
using Masuit.MyBlogs.Core.Common;
using Masuit.MyBlogs.Core.Configs;
using Masuit.MyBlogs.Core.Extensions.Hangfire;
using Masuit.MyBlogs.Core.Infrastructure.Services.Interface;
Expand Down
2 changes: 1 addition & 1 deletion src/Masuit.MyBlogs.Core/Masuit.MyBlogs.Core.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@
<PackageReference Include="MiniProfiler.EntityFrameworkCore" Version="4.2.22" />
<PackageReference Include="PanGu.HighLight" Version="1.0.0" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="6.0.1" />
<PackageReference Include="System.Linq.Dynamic.Core" Version="1.2.15" />
<PackageReference Include="System.Linq.Dynamic.Core" Version="1.2.17" />
<PackageReference Include="TimeZoneConverter" Version="5.0.0" />
<PackageReference Include="WilderMinds.RssSyndication" Version="1.7.0" />
<PackageReference Include="Z.EntityFramework.Plus.EFCore" Version="6.13.10" />
Expand Down
2 changes: 1 addition & 1 deletion src/Masuit.MyBlogs.Core/Views/Home/Index.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@
<a asp-controller="Notice" asp-action="Details" asp-route-id="@(Model.Notices.FirstOrDefault()?.Id)">
<h3 class="size18 text-red text-center">网站最新公告</h3>
</a>
@Html.Raw(Model.Notices[0].Content.Replace("img src=", $"img class='lazyload' title='{CommonHelper.SystemSettings["Title"]}' alt='{CommonHelper.SystemSettings["Title"]}' loading='lazy' data-src="))
@Html.Raw(Model.Notices[0].Content.Replace("img src=", $"img class='lazyload' title='{CommonHelper.SystemSettings["Title"]}' alt='{CommonHelper.SystemSettings["Title"]}' decoding='async' loading='lazy' data-src="))
</div>
}
@if (shares.Any())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
if (!string.IsNullOrEmpty(imgSrc))
{
<div class="col-md-2 paddingright-clear hidden-xs">
<img class="img-thumbnail img-responsive thumb lazyload" loading="lazy" data-src="@imgSrc" alt="@CommonHelper.SystemSettings["Title"]" title="@CommonHelper.SystemSettings["Title"] ">
<img class="img-thumbnail img-responsive thumb lazyload" decoding="async" loading="lazy" data-src="@imgSrc" alt="@CommonHelper.SystemSettings["Title"]" title="@CommonHelper.SystemSettings["Title"] ">
</div>
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
if (!string.IsNullOrEmpty(imgSrc))
{
<div class="col-sm-2 paddingright-clear hidden-xs">
<img class="img-thumbnail img-responsive thumb lazyload" loading="lazy" data-src="@imgSrc" alt="@Model.Title">
<img class="img-thumbnail img-responsive thumb lazyload" decoding="async" loading="lazy" data-src="@imgSrc" alt="@Model.Title">
</div>
}
}
Expand Down
14 changes: 9 additions & 5 deletions src/Masuit.MyBlogs.Core/Views/Shared/_Layout.cshtml
Original file line number Diff line number Diff line change
@@ -1,16 +1,20 @@
@using Masuit.MyBlogs.Core.Common
@inject IMenuService _menuService;
@inject ILinksService _linksService;
@using Masuit.MyBlogs.Core.Common
@using Masuit.MyBlogs.Core.Infrastructure.Services.Interface
@using Masuit.MyBlogs.Core.Models.DTO
@using Masuit.MyBlogs.Core.Models.Entity
@using Masuit.MyBlogs.Core.Models.Enum
@using Masuit.MyBlogs.Core.Models.ViewModel
@using Masuit.MyBlogs.Core.Views.Shared
@using Masuit.Tools
@using Masuit.Tools.Core.Net
@using EFCoreSecondLevelCacheInterceptor
@{
string[] colors = { "success", "info", "warning", "danger", "default" };
List<Menu> menus = ViewBag.menus;
UserInfoDto user = Context.Session.Get<UserInfoDto>(SessionKey.UserInfo) ?? new UserInfoDto();
PageFootViewModel footer = ViewBag.Footer;
List<Menu> menus = _menuService.GetQueryFromCache(m => m.ParentId == null && m.Status == Status.Available).OrderBy(m => m.Sort).ToList();
var user = Context.Session.Get<UserInfoDto>(SessionKey.UserInfo) ?? new UserInfoDto();
var links = _linksService.GetQuery(l => l.Status == Status.Available).OrderByDescending(l => l.Recommend).ThenByDescending(l => l.Loopbacks.Count).Take(30).Select(e => new{e.Url,e.Name}).Cacheable().ToList();
}

<!DOCTYPE html>
Expand Down Expand Up @@ -290,7 +294,7 @@
<a href="/taskcenter" target="_blank">任务管理器</a>
<span> | </span>
}
foreach (var link in footer.Links)
foreach (var link in links)
{
<a href="@link.Url" target="_blank" referrerpolicy="unsafe-url">@link.Name</a>
<span> | </span>
Expand Down

0 comments on commit f02e5ad

Please sign in to comment.