Sfoglia il codice sorgente

升级到.NET Core 3.0

懒得勤快 6 anni fa
parent
commit
861359d290
32 ha cambiato i file con 267 aggiunte e 231 eliminazioni
  1. 1 1
      src/Masuit.MyBlogs.Core/Common/CommonHelper.cs
  2. 19 0
      src/Masuit.MyBlogs.Core/Configs/AutofacModule.cs
  3. 0 30
      src/Masuit.MyBlogs.Core/Configs/GitlabConfig.cs
  4. 1 1
      src/Masuit.MyBlogs.Core/Configs/HangfireJobInit.cs
  5. 2 4
      src/Masuit.MyBlogs.Core/Controllers/BaseController.cs
  6. 3 4
      src/Masuit.MyBlogs.Core/Controllers/CommentController.cs
  7. 2 3
      src/Masuit.MyBlogs.Core/Controllers/DashboardController.cs
  8. 6 6
      src/Masuit.MyBlogs.Core/Controllers/FileController.cs
  9. 5 6
      src/Masuit.MyBlogs.Core/Controllers/HomeController.cs
  10. 1 1
      src/Masuit.MyBlogs.Core/Controllers/LinksController.cs
  11. 3 3
      src/Masuit.MyBlogs.Core/Controllers/MergeController.cs
  12. 5 5
      src/Masuit.MyBlogs.Core/Controllers/MiscController.cs
  13. 4 4
      src/Masuit.MyBlogs.Core/Controllers/MsgController.cs
  14. 5 5
      src/Masuit.MyBlogs.Core/Controllers/NoticeController.cs
  15. 5 7
      src/Masuit.MyBlogs.Core/Controllers/PassportController.cs
  16. 17 18
      src/Masuit.MyBlogs.Core/Controllers/PostController.cs
  17. 2 2
      src/Masuit.MyBlogs.Core/Controllers/SearchController.cs
  18. 1 1
      src/Masuit.MyBlogs.Core/Controllers/SeminarController.cs
  19. 2 2
      src/Masuit.MyBlogs.Core/Controllers/SubscribeController.cs
  20. 0 1
      src/Masuit.MyBlogs.Core/Controllers/SystemController.cs
  21. 3 3
      src/Masuit.MyBlogs.Core/Controllers/ToolsController.cs
  22. 9 9
      src/Masuit.MyBlogs.Core/Controllers/UploadController.cs
  23. 2 1
      src/Masuit.MyBlogs.Core/Extensions/AuthorityAttribute.cs
  24. 5 5
      src/Masuit.MyBlogs.Core/Extensions/Hangfire/HangfireBackJob.cs
  25. 108 0
      src/Masuit.MyBlogs.Core/Extensions/MiddlewareExtension.cs
  26. 1 1
      src/Masuit.MyBlogs.Core/Extensions/UEditor/CrawlerHandler.cs
  27. 1 1
      src/Masuit.MyBlogs.Core/Extensions/UEditor/UploadHandler.cs
  28. 12 10
      src/Masuit.MyBlogs.Core/Masuit.MyBlogs.Core.csproj
  29. 17 12
      src/Masuit.MyBlogs.Core/Program.cs
  30. 21 81
      src/Masuit.MyBlogs.Core/Startup.cs
  31. 2 2
      src/Masuit.MyBlogs.Core/Views/Error/Index.cshtml
  32. 2 2
      src/Masuit.MyBlogs.Core/Views/Error/ServiceUnavailable.cshtml

+ 1 - 1
src/Masuit.MyBlogs.Core/Common/CommonHelper.cs

@@ -171,7 +171,7 @@ namespace Masuit.MyBlogs.Core.Common
         /// <typeparam name="T"></typeparam>
         /// <param name="source"></param>
         /// <returns></returns>
-        public static T Mapper<T>(this object source) where T : class => Startup.AutofacContainer.GetRequiredService<IMapper>().Map<T>(source);
+        public static T Mapper<T>(this object source) where T : class => Startup.ServiceProvider.GetRequiredService<IMapper>().Map<T>(source);
 
         /// <summary>
         /// 发送邮件

+ 19 - 0
src/Masuit.MyBlogs.Core/Configs/AutofacModule.cs

@@ -0,0 +1,19 @@
+using Autofac;
+using Hangfire;
+using Masuit.MyBlogs.Core.Extensions;
+using Masuit.MyBlogs.Core.Extensions.Hangfire;
+using System.Reflection;
+
+namespace Masuit.MyBlogs.Core.Configs
+{
+    public class AutofacModule : Autofac.Module
+    {
+        protected override void Load(ContainerBuilder builder)
+        {
+            builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).AsImplementedInterfaces().Where(t => t.Name.EndsWith("Repository") || t.Name.EndsWith("Service") || t.Name.EndsWith("Controller") || t.Name.EndsWith("Attribute")).PropertiesAutowired().AsSelf().InstancePerDependency();
+            builder.RegisterType<BackgroundJobClient>().SingleInstance();
+            builder.RegisterType<FirewallAttribute>().PropertiesAutowired().AsSelf().InstancePerDependency();
+            builder.RegisterType<HangfireBackJob>().As<IHangfireBackJob>().PropertiesAutowired(PropertyWiringOptions.PreserveSetValues).InstancePerDependency();
+        }
+    }
+}

+ 0 - 30
src/Masuit.MyBlogs.Core/Configs/GitlabConfig.cs

@@ -9,35 +9,5 @@
         public string AccessToken { get; set; }
         public string Branch { get; set; }
         public int FileLimitSize { get; set; }
-
-        /// <summary>Determines whether the specified object is equal to the current object.</summary>
-        /// <param name="obj">The object to compare with the current object.</param>
-        /// <returns>true if the specified object  is equal to the current object; otherwise, false.</returns>
-        public override bool Equals(object obj)
-        {
-            return AccessToken == ((GitlabConfig)obj).AccessToken;
-        }
-
-        /// <summary>
-        /// 判等
-        /// </summary>
-        /// <param name="x"></param>
-        /// <param name="y"></param>
-        /// <returns></returns>
-        public static bool operator ==(GitlabConfig x, GitlabConfig y)
-        {
-            return x?.AccessToken == y?.AccessToken;
-        }
-
-        /// <summary>
-        /// 判不等
-        /// </summary>
-        /// <param name="x"></param>
-        /// <param name="y"></param>
-        /// <returns></returns>
-        public static bool operator !=(GitlabConfig x, GitlabConfig y)
-        {
-            return x?.AccessToken != y?.AccessToken;
-        }
     }
 }

+ 1 - 1
src/Masuit.MyBlogs.Core/Configs/HangfireJobInit.cs

@@ -15,7 +15,7 @@ namespace Masuit.MyBlogs.Core.Configs
         /// </summary>
         public static void Start()
         {
-            RecurringJob.AddOrUpdate(() => CheckLinks(), Cron.HourInterval(5)); //每5h检查友链
+            RecurringJob.AddOrUpdate(() => CheckLinks(), "0 */5 * * *"); //每5h检查友链
             RecurringJob.AddOrUpdate(() => EverydayJob(), Cron.Daily(5), TimeZoneInfo.Local); //每天的任务
             RecurringJob.AddOrUpdate(() => EveryweekJob(), Cron.Weekly(DayOfWeek.Monday, 5), TimeZoneInfo.Local); //每周的任务
             RecurringJob.AddOrUpdate(() => EveryHourJob(), Cron.Hourly); //每小时的任务

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

@@ -1,6 +1,4 @@
 using AutoMapper;
-using AutoMapper.QueryableExtensions;
-using EFSecondLevelCache.Core;
 using Masuit.MyBlogs.Core.Common;
 using Masuit.MyBlogs.Core.Configs;
 using Masuit.MyBlogs.Core.Extensions;
@@ -143,9 +141,9 @@ namespace Masuit.MyBlogs.Core.Controllers
             #region 准备页面数据模型
 
             ViewBag.menus = MenuService.GetQueryFromCache<MenuOutputDto>(m => m.Status == Status.Available).OrderBy(m => m.Sort).ToList(); //菜单
-            PageFootViewModel model = new PageFootViewModel //页脚
+            var model = new PageFootViewModel //页脚
             {
-                Links = LinksService.GetQuery(l => l.Status == Status.Available, l => l.Recommend, false).ThenByDescending(l => l.Weight).ThenByDescending(l => new Random().Next()).Take(40).ProjectTo<LinksOutputDto>(MapperConfig).Cacheable().ToList()
+                Links = LinksService.GetQueryFromCache<LinksOutputDto>(l => l.Status == Status.Available).OrderBy(l => l.Recommend).ThenByDescending(l => l.Weight).ThenByDescending(l => new Random().Next()).Take(40).ToList()
             };
             ViewBag.Footer = model;
 

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

@@ -6,7 +6,6 @@ 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.Tools;
 using Masuit.Tools.Core.Net;
 using Masuit.Tools.Html;
 using Microsoft.AspNetCore.Hosting;
@@ -30,7 +29,7 @@ namespace Masuit.MyBlogs.Core.Controllers
         public ICommentService CommentService { get; set; }
         public IPostService PostService { get; set; }
         public IInternalMessageService MessageService { get; set; }
-        public IHostingEnvironment HostingEnvironment { get; set; }
+        public IWebHostEnvironment HostEnvironment { get; set; }
 
         /// <summary>
         /// 发表评论
@@ -95,7 +94,7 @@ namespace Masuit.MyBlogs.Core.Controllers
             var emails = new HashSet<string>();
             var email = CommonHelper.SystemSettings["ReceiveEmail"]; //站长邮箱
             emails.Add(email);
-            var content = System.IO.File.ReadAllText(HostingEnvironment.WebRootPath + "/template/notify.html")
+            var content = System.IO.File.ReadAllText(HostEnvironment.WebRootPath + "/template/notify.html")
                 .Replace("{{title}}", post.Title)
                 .Replace("{{time}}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))
                 .Replace("{{nickname}}", comment.NickName)
@@ -237,7 +236,7 @@ namespace Masuit.MyBlogs.Core.Controllers
             {
                 var pid = comment.ParentId == 0 ? comment.Id : CommentService.GetParentCommentIdByChildId(id);
 #if !DEBUG
-                var content = System.IO.File.ReadAllText(Path.Combine(HostingEnvironment.WebRootPath, "template", "notify.html"))
+                var content = System.IO.File.ReadAllText(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)

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

@@ -3,7 +3,6 @@ using Masuit.MyBlogs.Core.Infrastructure.Services.Interface;
 using Masuit.MyBlogs.Core.Models.Enum;
 using Masuit.Tools.Logging;
 using Microsoft.AspNetCore.Mvc;
-using Microsoft.Net.Http.Headers;
 using System.Collections.Generic;
 using System.IO;
 using System.Linq;
@@ -32,7 +31,7 @@ namespace Masuit.MyBlogs.Core.Controllers
         /// 控制面板
         /// </summary>
         /// <returns></returns>
-        [Route("dashboard"), ResponseCache(Duration = 60, VaryByHeader = HeaderNames.Cookie)]
+        [Route("dashboard"), ResponseCache(Duration = 60, VaryByHeader = "Cookie")]
         public ActionResult Index()
         {
             return View();
@@ -119,7 +118,7 @@ namespace Masuit.MyBlogs.Core.Controllers
         /// 资源管理器
         /// </summary>
         /// <returns></returns>
-        [Route("filemanager"), ResponseCache(Duration = 60, VaryByHeader = HeaderNames.Cookie)]
+        [Route("filemanager"), ResponseCache(Duration = 60, VaryByHeader = "Cookie")]
         public ActionResult FileManager()
         {
             return View();

+ 6 - 6
src/Masuit.MyBlogs.Core/Controllers/FileController.cs

@@ -18,7 +18,7 @@ namespace Masuit.MyBlogs.Core.Controllers
     [Route("[controller]/[action]")]
     public class FileController : AdminController
     {
-        public IHostingEnvironment HostingEnvironment { get; set; }
+        public IWebHostEnvironment HostEnvironment { get; set; }
         /// <summary>
         /// 
         /// </summary>
@@ -31,7 +31,7 @@ namespace Masuit.MyBlogs.Core.Controllers
         /// <returns></returns>
         public ActionResult GetFiles(string path)
         {
-            var files = Directory.GetFiles(HostingEnvironment.WebRootPath + path).OrderByDescending(s => s).Select(s => new
+            var files = Directory.GetFiles(HostEnvironment.WebRootPath + path).OrderByDescending(s => s).Select(s => new
             {
                 filename = Path.GetFileName(s),
                 path = s
@@ -86,7 +86,7 @@ namespace Masuit.MyBlogs.Core.Controllers
             {
                 foreach (var t in Request.Form.Files)
                 {
-                    string path = Path.Combine(HostingEnvironment.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);
@@ -108,7 +108,7 @@ namespace Masuit.MyBlogs.Core.Controllers
         public ActionResult Handle([FromBody]FileRequest req)
         {
             List<object> list = new List<object>();
-            var root = Path.Combine(HostingEnvironment.ContentRootPath, CommonHelper.SystemSettings["PathRoot"].TrimStart('\\', '/'));
+            var root = Path.Combine(HostEnvironment.ContentRootPath, CommonHelper.SystemSettings["PathRoot"].TrimStart('\\', '/'));
             switch (req.Action)
             {
                 case "list":
@@ -274,7 +274,7 @@ namespace Masuit.MyBlogs.Core.Controllers
         {
             path = path?.TrimStart('\\', '/') ?? "";
             var root = CommonHelper.SystemSettings["PathRoot"].TrimStart('\\', '/');
-            var file = Path.Combine(HostingEnvironment.ContentRootPath, root, path);
+            var file = Path.Combine(HostEnvironment.ContentRootPath, root, path);
             switch (Request.Query["action"])
             {
                 case "download":
@@ -284,7 +284,7 @@ namespace Masuit.MyBlogs.Core.Controllers
                     }
                     break;
                 case "downloadMultiple":
-                    byte[] buffer = SevenZipCompressor.ZipStream(items.Select(s => Path.Combine(HostingEnvironment.ContentRootPath, root, s.TrimStart('\\', '/'))).ToList()).ToArray();
+                    byte[] buffer = SevenZipCompressor.ZipStream(items.Select(s => Path.Combine(HostEnvironment.ContentRootPath, root, s.TrimStart('\\', '/'))).ToList()).ToArray();
                     return this.ResumeFile(buffer, Path.GetFileName(toFilename));
             }
             return Content("null");

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

@@ -6,7 +6,6 @@ using Masuit.MyBlogs.Core.Models.DTO;
 using Masuit.MyBlogs.Core.Models.Enum;
 using Masuit.MyBlogs.Core.Models.ViewModel;
 using Microsoft.AspNetCore.Mvc;
-using Microsoft.Net.Http.Headers;
 using System;
 using System.Collections.Generic;
 using System.ComponentModel.DataAnnotations;
@@ -51,7 +50,7 @@ namespace Masuit.MyBlogs.Core.Controllers
         /// 首页
         /// </summary>
         /// <returns></returns>
-        [HttpGet, ResponseCache(Duration = 600, VaryByQueryKeys = new[] { "orderBy" }, VaryByHeader = HeaderNames.Cookie)]
+        [HttpGet, ResponseCache(Duration = 600, VaryByQueryKeys = new[] { "orderBy" }, VaryByHeader = "Cookie")]
         public ActionResult Index()
         {
             ViewBag.Total = PostService.Count(p => p.Status == Status.Pended || CurrentUser.IsAdmin);
@@ -70,7 +69,7 @@ namespace Masuit.MyBlogs.Core.Controllers
         /// <param name="size"></param>
         /// <param name="orderBy"></param>
         /// <returns></returns>
-        [Route("p"), ResponseCache(Duration = 600, VaryByQueryKeys = new[] { "page", "size", "orderBy" }, VaryByHeader = HeaderNames.Cookie)]
+        [Route("p"), ResponseCache(Duration = 600, VaryByQueryKeys = new[] { "page", "size", "orderBy" }, VaryByHeader = "Cookie")]
         public ActionResult Post([Optional]OrderBy? orderBy, [Range(1, int.MaxValue, ErrorMessage = "页码必须大于0")]int page = 1, [Range(1, int.MaxValue, ErrorMessage = "页大小必须大于0")]int size = 15)
         {
             ViewBag.Total = PostService.Count(p => p.Status == Status.Pended || CurrentUser.IsAdmin && !p.IsFixedTop);
@@ -86,7 +85,7 @@ namespace Masuit.MyBlogs.Core.Controllers
         /// <param name="size"></param>
         /// <param name="orderBy"></param>
         /// <returns></returns>
-        [Route("tag/{id}/{page:int?}/{size:int?}/{orderBy:int?}"), ResponseCache(Duration = 600, VaryByQueryKeys = new[] { "id", "page", "size", "orderBy" }, VaryByHeader = HeaderNames.Cookie)]
+        [Route("tag/{id}/{page:int?}/{size:int?}/{orderBy:int?}"), ResponseCache(Duration = 600, VaryByQueryKeys = new[] { "id", "page", "size", "orderBy" }, VaryByHeader = "Cookie")]
         public ActionResult Tag(string id, [Optional]OrderBy? orderBy, [Range(1, int.MaxValue, ErrorMessage = "页码必须大于0")]int page = 1, [Range(1, int.MaxValue, ErrorMessage = "页大小必须大于0")]int size = 15)
         {
             IList<PostOutputDto> posts;
@@ -127,7 +126,7 @@ namespace Masuit.MyBlogs.Core.Controllers
         /// <param name="size"></param>
         /// <param name="orderBy"></param>
         /// <returns></returns>
-        [Route("cat/{id:int}"), ResponseCache(Duration = 600, VaryByQueryKeys = new[] { "id", "page", "size", "orderBy" }, VaryByHeader = HeaderNames.Cookie)]
+        [Route("cat/{id:int}"), ResponseCache(Duration = 600, VaryByQueryKeys = new[] { "id", "page", "size", "orderBy" }, VaryByHeader = "Cookie")]
         [Route("cat/{id:int}/{page:int?}/{size:int?}/{orderBy:int?}")]
         public async Task<ActionResult> Category(int id, [Optional]OrderBy? orderBy, [Range(1, int.MaxValue, ErrorMessage = "页码必须大于0")]int page = 1, [Range(1, int.MaxValue, ErrorMessage = "页大小必须大于0")]int size = 15)
         {
@@ -188,7 +187,7 @@ namespace Masuit.MyBlogs.Core.Controllers
             }
             var hot6Post = postsQuery.OrderByDescending(order).Skip(0).Take(5).Cacheable().ToList(); //热门文章
             var newdic = new Dictionary<string, int>(); //标签云最终结果
-            var tagdic = postsQuery.Where(p => !string.IsNullOrEmpty(p.Label)).Select(p => p.Label).Cacheable().SelectMany(s => s.Split(',', ',')).GroupBy(s => s).ToDictionary(g => g.Key, g => g.Count()); //统计标签
+            var tagdic = postsQuery.Where(p => !string.IsNullOrEmpty(p.Label)).Select(p => p.Label).Cacheable().AsEnumerable().SelectMany(s => s.Split(',', ',')).GroupBy(s => s).ToDictionary(g => g.Key, g => g.Count()); //统计标签
 
             if (tagdic.Any())
             {

+ 1 - 1
src/Masuit.MyBlogs.Core/Controllers/LinksController.cs

@@ -27,7 +27,7 @@ namespace Masuit.MyBlogs.Core.Controllers
         /// 友情链接页
         /// </summary>
         /// <returns></returns>
-        [Route("links"), ResponseCache(Duration = 600, VaryByHeader = HeaderNames.Cookie)]
+        [Route("links"), ResponseCache(Duration = 600, VaryByHeader = "Cookie")]
         public ActionResult Index()
         {
             var list = LinksService.GetQueryFromCache<bool, LinksOutputDto>(l => l.Status == Status.Available, l => l.Recommend, false).ToList();

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

@@ -21,7 +21,7 @@ namespace Masuit.MyBlogs.Core.Controllers
     public class MergeController : AdminController
     {
         public IPostMergeRequestService PostMergeRequestService { get; set; }
-        public IHostingEnvironment HostingEnvironment { get; set; }
+        public IWebHostEnvironment HostEnvironment { get; set; }
         public MapperConfiguration MapperConfig { get; set; }
 
         /// <summary>
@@ -96,7 +96,7 @@ namespace Masuit.MyBlogs.Core.Controllers
             }
 
             string link = Request.Scheme + "://" + Request.Host + "/" + merge.Post.Id;
-            string content = System.IO.File.ReadAllText(HostingEnvironment.WebRootPath + "/template/merge-pass.html").Replace("{{link}}", link).Replace("{{title}}", merge.Post.Title);
+            string content = System.IO.File.ReadAllText(HostEnvironment.WebRootPath + "/template/merge-pass.html").Replace("{{link}}", link).Replace("{{title}}", merge.Post.Title);
             BackgroundJob.Enqueue(() => CommonHelper.SendMail(CommonHelper.SystemSettings["Title"] + "博客你提交的修改已通过", content, merge.ModifierEmail));
             return ResultData(null, true, "文章合并完成!");
 
@@ -139,7 +139,7 @@ namespace Masuit.MyBlogs.Core.Controllers
             }
 
             var link = Request.Scheme + "://" + Request.Host + "/" + merge.Post.Id + "/merge/" + id;
-            var content = System.IO.File.ReadAllText(HostingEnvironment.WebRootPath + "/template/merge-reject.html").Replace("{{link}}", link).Replace("{{title}}", merge.Post.Title).Replace("{{reason}}", reason);
+            var content = System.IO.File.ReadAllText(HostEnvironment.WebRootPath + "/template/merge-reject.html").Replace("{{link}}", link).Replace("{{title}}", merge.Post.Title).Replace("{{reason}}", reason);
             BackgroundJob.Enqueue(() => CommonHelper.SendMail(CommonHelper.SystemSettings["Title"] + "博客你提交的修改已被拒绝", content, merge.ModifierEmail));
             return ResultData(null, true, "合并已拒绝!");
         }

+ 5 - 5
src/Masuit.MyBlogs.Core/Controllers/MiscController.cs

@@ -31,7 +31,7 @@ namespace Masuit.MyBlogs.Core.Controllers
         /// </summary>
         public IDonateService DonateService { get; set; }
 
-        public IHostingEnvironment HostingEnvironment { get; set; }
+        public IWebHostEnvironment HostEnvironment { get; set; }
         public ImagebedClient ImagebedClient { get; set; }
 
         /// <summary>
@@ -39,7 +39,7 @@ namespace Masuit.MyBlogs.Core.Controllers
         /// </summary>
         /// <param name="id"></param>
         /// <returns></returns>
-        [Route("misc/{id:int}"), ResponseCache(Duration = 600, VaryByQueryKeys = new[] { "id" }, VaryByHeader = HeaderNames.Cookie)]
+        [Route("misc/{id:int}"), ResponseCache(Duration = 600, VaryByQueryKeys = new[] { "id" }, VaryByHeader = "Cookie")]
         public ActionResult Index(int id)
         {
             var misc = MiscService.GetFromCache(m => m.Id == id) ?? throw new NotFoundException("页面未找到");
@@ -82,7 +82,7 @@ namespace Masuit.MyBlogs.Core.Controllers
         /// 关于
         /// </summary>
         /// <returns></returns>
-        [Route("about"), ResponseCache(Duration = 600, VaryByHeader = HeaderNames.Cookie)]
+        [Route("about"), ResponseCache(Duration = 600, VaryByHeader = "Cookie")]
         public ActionResult About()
         {
             return View();
@@ -92,7 +92,7 @@ namespace Masuit.MyBlogs.Core.Controllers
         /// 声明
         /// </summary>
         /// <returns></returns>
-        [Route("disclaimer"), ResponseCache(Duration = 600, VaryByHeader = HeaderNames.Cookie)]
+        [Route("disclaimer"), ResponseCache(Duration = 600, VaryByHeader = "Cookie")]
         public ActionResult Disclaimer()
         {
             return View();
@@ -134,7 +134,7 @@ namespace Masuit.MyBlogs.Core.Controllers
             {
                 try
                 {
-                    System.IO.File.Delete(Path.Combine(HostingEnvironment.WebRootPath + path));
+                    System.IO.File.Delete(Path.Combine(HostEnvironment.WebRootPath + path));
                 }
                 catch (IOException)
                 {

+ 4 - 4
src/Masuit.MyBlogs.Core/Controllers/MsgController.cs

@@ -35,13 +35,13 @@ namespace Masuit.MyBlogs.Core.Controllers
         /// </summary>
         public IInternalMessageService MessageService { get; set; }
 
-        public IHostingEnvironment HostingEnvironment { get; set; }
+        public IWebHostEnvironment HostEnvironment { get; set; }
 
         /// <summary>
         /// 留言板
         /// </summary>
         /// <returns></returns>
-        [ResponseCache(Duration = 600, VaryByHeader = HeaderNames.Cookie), Route("msg")]
+        [ResponseCache(Duration = 600, VaryByHeader = "Cookie"), Route("msg")]
         public ActionResult Index()
         {
             ViewBag.TotalCount = LeaveMessageService.GetQueryNoTracking(m => m.ParentId == 0 && m.Status == Status.Pended).Count();
@@ -147,7 +147,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(HostingEnvironment.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 = 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);
             if (msg.Status == Status.Pended)
             {
                 if (!msg.IsMaster)
@@ -200,7 +200,7 @@ 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(HostingEnvironment.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 = 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 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)

+ 5 - 5
src/Masuit.MyBlogs.Core/Controllers/NoticeController.cs

@@ -28,7 +28,7 @@ namespace Masuit.MyBlogs.Core.Controllers
         /// </summary>
         public INoticeService NoticeService { get; set; }
 
-        public IHostingEnvironment HostingEnvironment { get; set; }
+        public IWebHostEnvironment HostEnvironment { get; set; }
 
         public ImagebedClient ImagebedClient { get; set; }
 
@@ -39,7 +39,7 @@ namespace Masuit.MyBlogs.Core.Controllers
         /// <param name="size"></param>
         /// <param name="id"></param>
         /// <returns></returns>
-        [Route("notice"), ResponseCache(Duration = 60, VaryByQueryKeys = new[] { "page", "size", "id" }, VaryByHeader = HeaderNames.Cookie)]
+        [Route("notice"), ResponseCache(Duration = 60, VaryByQueryKeys = new[] { "page", "size", "id" }, VaryByHeader = "Cookie")]
         public ActionResult Index(int page = 1, int size = 10, int id = 0)
         {
             var list = NoticeService.GetPages<DateTime, NoticeOutputDto>(page, size, out var total, n => n.Status == Status.Display, n => n.ModifyDate, false).ToList();
@@ -68,7 +68,7 @@ namespace Masuit.MyBlogs.Core.Controllers
         /// </summary>
         /// <param name="id"></param>
         /// <returns></returns>
-        [Route("n/{id:int}"), ResponseCache(Duration = 600, VaryByQueryKeys = new[] { "id" }, VaryByHeader = HeaderNames.Cookie)]
+        [Route("n/{id:int}"), ResponseCache(Duration = 600, VaryByQueryKeys = new[] { "id" }, VaryByHeader = "Cookie")]
         public ActionResult Details(int id)
         {
             var notice = NoticeService.GetById(id) ?? throw new NotFoundException("页面未找到");
@@ -111,7 +111,7 @@ namespace Masuit.MyBlogs.Core.Controllers
             {
                 try
                 {
-                    System.IO.File.Delete(HostingEnvironment.WebRootPath + path);
+                    System.IO.File.Delete(HostEnvironment.WebRootPath + path);
                 }
                 catch
                 {
@@ -175,7 +175,7 @@ namespace Masuit.MyBlogs.Core.Controllers
         /// 最近一条公告
         /// </summary>
         /// <returns></returns>
-        [ResponseCache(Duration = 600, VaryByHeader = HeaderNames.Cookie)]
+        [ResponseCache(Duration = 600, VaryByHeader = "Cookie")]
         public ActionResult Last()
         {
             if (HttpContext.Session.Get("last-notice") != null)

+ 5 - 7
src/Masuit.MyBlogs.Core/Controllers/PassportController.cs

@@ -10,7 +10,6 @@ using Masuit.Tools.AspNetCore.ResumeFileResults.Extensions;
 using Masuit.Tools.Core.Net;
 using Masuit.Tools.Security;
 using Masuit.Tools.Strings;
-using Microsoft.AspNetCore.Hosting;
 using Microsoft.AspNetCore.Http;
 using Microsoft.AspNetCore.Mvc;
 using System;
@@ -28,7 +27,6 @@ namespace Masuit.MyBlogs.Core.Controllers
         /// 用户
         /// </summary>
         public IUserInfoService UserInfoService { get; set; }
-        public IHostingEnvironment HostingEnvironment { get; set; }
 
         /// <summary>
         /// 
@@ -159,11 +157,11 @@ namespace Masuit.MyBlogs.Core.Controllers
         /// <returns></returns>
         public ActionResult GetUserInfo()
         {
-            UserInfoOutputDto user = HttpContext.Session.Get<UserInfoOutputDto>(SessionKey.UserInfo);
-            if (HostingEnvironment.IsDevelopment())
-            {
-                user = UserInfoService.GetByUsername("masuit").Mapper<UserInfoOutputDto>();
-            }
+            var user = HttpContext.Session.Get<UserInfoOutputDto>(SessionKey.UserInfo);
+#if DEBUG
+            user = UserInfoService.GetByUsername("masuit").Mapper<UserInfoOutputDto>();
+#endif
+
             return ResultData(user);
         }
 

+ 17 - 18
src/Masuit.MyBlogs.Core/Controllers/PostController.cs

@@ -24,7 +24,6 @@ using Microsoft.AspNetCore.Http;
 using Microsoft.AspNetCore.Mvc;
 using Microsoft.AspNetCore.Mvc.Rendering;
 using Microsoft.EntityFrameworkCore.Internal;
-using Microsoft.Net.Http.Headers;
 using System;
 using System.ComponentModel.DataAnnotations;
 using System.IO;
@@ -48,7 +47,7 @@ namespace Masuit.MyBlogs.Core.Controllers
 
         public IInternalMessageService MessageService { get; set; }
 
-        public IHostingEnvironment HostingEnvironment { get; set; }
+        public IWebHostEnvironment HostEnvironment { get; set; }
         public ISearchEngine<DataContext> SearchEngine { get; set; }
         public ImagebedClient ImagebedClient { get; set; }
 
@@ -58,7 +57,7 @@ namespace Masuit.MyBlogs.Core.Controllers
         /// <param name="id"></param>
         /// <param name="kw"></param>
         /// <returns></returns>
-        [Route("{id:int}/{kw}"), Route("{id:int}"), ResponseCache(Duration = 600, VaryByQueryKeys = new[] { "id" }, VaryByHeader = HeaderNames.Cookie)]
+        [Route("{id:int}/{kw}"), Route("{id:int}"), ResponseCache(Duration = 600, VaryByQueryKeys = new[] { "id" }, VaryByHeader = "Cookie")]
         public ActionResult Details(int id, string kw)
         {
             var post = PostService.Get(p => p.Id == id && (p.Status == Status.Pended || CurrentUser.IsAdmin)) ?? throw new NotFoundException("文章未找到");
@@ -92,7 +91,7 @@ namespace Masuit.MyBlogs.Core.Controllers
         /// <param name="page"></param>
         /// <param name="size"></param>
         /// <returns></returns>
-        [Route("{id:int}/history"), Route("{id:int}/history/{page:int}/{size:int}"), ResponseCache(Duration = 600, VaryByQueryKeys = new[] { "id", "page", "size" }, VaryByHeader = HeaderNames.Cookie)]
+        [Route("{id:int}/history"), Route("{id:int}/history/{page:int}/{size:int}"), ResponseCache(Duration = 600, VaryByQueryKeys = new[] { "id", "page", "size" }, VaryByHeader = "Cookie")]
         public ActionResult History(int id, int page = 1, int size = 20)
         {
             var post = PostService.Get(p => p.Id == id && (p.Status == Status.Pended || CurrentUser.IsAdmin)).Mapper<PostOutputDto>() ?? throw new NotFoundException("文章未找到");
@@ -109,7 +108,7 @@ namespace Masuit.MyBlogs.Core.Controllers
         /// <param name="id"></param>
         /// <param name="hid"></param>
         /// <returns></returns>
-        [Route("{id:int}/history/{hid:int}"), ResponseCache(Duration = 600, VaryByQueryKeys = new[] { "id", "hid" }, VaryByHeader = HeaderNames.Cookie)]
+        [Route("{id:int}/history/{hid:int}"), ResponseCache(Duration = 600, VaryByQueryKeys = new[] { "id", "hid" }, VaryByHeader = "Cookie")]
         public ActionResult HistoryVersion(int id, int hid)
         {
             var post = PostHistoryVersionService.Get(v => v.Id == hid) ?? throw new NotFoundException("文章未找到");
@@ -125,7 +124,7 @@ namespace Masuit.MyBlogs.Core.Controllers
         /// <param name="v1"></param>
         /// <param name="v2"></param>
         /// <returns></returns>
-        [Route("{id:int}/history/{v1:int}-{v2:int}"), ResponseCache(Duration = 600, VaryByQueryKeys = new[] { "id", "v1", "v2" }, VaryByHeader = HeaderNames.Cookie)]
+        [Route("{id:int}/history/{v1:int}-{v2:int}"), ResponseCache(Duration = 600, VaryByQueryKeys = new[] { "id", "v1", "v2" }, VaryByHeader = "Cookie")]
         public ActionResult CompareVersion(int id, int v1, int v2)
         {
             var main = PostService.Get(p => p.Id == id && (p.Status == Status.Pended || CurrentUser.IsAdmin)).Mapper<PostHistoryVersion>() ?? throw new NotFoundException("文章未找到");
@@ -241,7 +240,7 @@ namespace Masuit.MyBlogs.Core.Controllers
             }
 
             RedisHelper.Expire("code:" + p.Email, 1);
-            var content = System.IO.File.ReadAllText(HostingEnvironment.WebRootPath + "/template/publish.html")
+            var content = System.IO.File.ReadAllText(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);
@@ -253,10 +252,10 @@ namespace Masuit.MyBlogs.Core.Controllers
         /// 获取标签
         /// </summary>
         /// <returns></returns>
-        [ResponseCache(Duration = 600, VaryByHeader = HeaderNames.Cookie)]
+        [ResponseCache(Duration = 600, VaryByHeader = "Cookie")]
         public ActionResult GetTag()
         {
-            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().AsEnumerable().SelectMany(s => s.Split(',', ',')).OrderBy(s => s).ToHashSet();
             return ResultData(list);
         }
 
@@ -264,10 +263,10 @@ namespace Masuit.MyBlogs.Core.Controllers
         /// 标签云
         /// </summary>
         /// <returns></returns>
-        [Route("all"), ResponseCache(Duration = 600, VaryByHeader = HeaderNames.Cookie)]
+        [Route("all"), ResponseCache(Duration = 600, VaryByHeader = "Cookie")]
         public ActionResult All()
         {
-            var tags = PostService.GetQuery(p => !string.IsNullOrEmpty(p.Label)).Select(p => p.Label).SelectMany(s => s.Split(',', ',')).OrderBy(s => s).Cacheable().ToList(); //tag
+            var tags = PostService.GetQuery(p => !string.IsNullOrEmpty(p.Label)).Select(p => p.Label).Cacheable().AsEnumerable().SelectMany(s => s.Split(',', ',')).OrderBy(s => s).ToList(); //tag
             ViewBag.tags = tags.GroupBy(t => t).OrderByDescending(g => g.Count()).ThenBy(g => g.Key);
             ViewBag.cats = CategoryService.GetAll(c => c.Post.Count, false).Select(c => new TagCloudViewModel
             {
@@ -432,7 +431,7 @@ namespace Masuit.MyBlogs.Core.Controllers
                 Content = dto.Title,
                 Link = "#/merge/compare?id=" + merge.Id
             });
-            var content = System.IO.File.ReadAllText(HostingEnvironment.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 = 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);
             BackgroundJob.Enqueue(() => CommonHelper.SendMail("博客文章修改请求:", content, CommonHelper.SystemSettings["ReceiveEmail"]));
 
             return ResultData(null, b, b ? "您的修改请求已提交,已进入审核状态,感谢您的参与!" : "操作失败!");
@@ -488,7 +487,7 @@ namespace Masuit.MyBlogs.Core.Controllers
             cast.ForEach(c =>
             {
                 var ts = DateTime.Now.GetTotalMilliseconds();
-                var content = System.IO.File.ReadAllText(HostingEnvironment.WebRootPath + "/template/broadcast.html")
+                var content = System.IO.File.ReadAllText(HostEnvironment.WebRootPath + "/template/broadcast.html")
                     .Replace("{{link}}", link + "?email=" + c.Email)
                     .Replace("{{time}}", post.ModifyDate.ToString("yyyy-MM-dd HH:mm:ss"))
                     .Replace("{{title}}", post.Title)
@@ -556,8 +555,8 @@ namespace Masuit.MyBlogs.Core.Controllers
             {
                 try
                 {
-                    System.IO.File.Delete(Path.Combine(HostingEnvironment.WebRootPath + "/upload", post.ResourceName));
-                    Directory.Delete(Path.Combine(HostingEnvironment.WebRootPath + "/upload", Path.GetFileNameWithoutExtension(post.ResourceName)), true);
+                    System.IO.File.Delete(Path.Combine(HostEnvironment.WebRootPath + "/upload", post.ResourceName));
+                    Directory.Delete(Path.Combine(HostEnvironment.WebRootPath + "/upload", Path.GetFileNameWithoutExtension(post.ResourceName)), true);
                 }
                 catch (IOException)
                 {
@@ -571,7 +570,7 @@ namespace Masuit.MyBlogs.Core.Controllers
                 {
                     try
                     {
-                        System.IO.File.Delete(HostingEnvironment.WebRootPath + path);
+                        System.IO.File.Delete(HostEnvironment.WebRootPath + path);
                     }
                     catch (IOException)
                     {
@@ -752,7 +751,7 @@ namespace Masuit.MyBlogs.Core.Controllers
                 cast.ForEach(c =>
                 {
                     var ts = DateTime.Now.GetTotalMilliseconds();
-                    string content = System.IO.File.ReadAllText(Path.Combine(HostingEnvironment.WebRootPath, "template", "broadcast.html"))
+                    string content = System.IO.File.ReadAllText(Path.Combine(HostEnvironment.WebRootPath, "template", "broadcast.html"))
                         .Replace("{{link}}", link + "?email=" + c.Email)
                         .Replace("{{time}}", post.ModifyDate.ToString("yyyy-MM-dd HH:mm:ss"))
                         .Replace("{{title}}", post.Title)
@@ -867,7 +866,7 @@ namespace Masuit.MyBlogs.Core.Controllers
             cast.ForEach(c =>
             {
                 var ts = DateTime.Now.GetTotalMilliseconds();
-                string content = System.IO.File.ReadAllText(HostingEnvironment.WebRootPath + "/template/broadcast.html")
+                string content = System.IO.File.ReadAllText(HostEnvironment.WebRootPath + "/template/broadcast.html")
                     .Replace("{{link}}", link + "?email=" + c.Email)
                     .Replace("{{time}}", post.ModifyDate.ToString("yyyy-MM-dd HH:mm:ss"))
                     .Replace("{{title}}", post.Title).Replace("{{author}}", post.Author)

+ 2 - 2
src/Masuit.MyBlogs.Core/Controllers/SearchController.cs

@@ -96,7 +96,7 @@ namespace Masuit.MyBlogs.Core.Controllers
         /// <param name="size"></param>
         /// <param name="search"></param>
         /// <returns></returns>
-        [Authority, HttpPost, ResponseCache(Duration = 600, VaryByQueryKeys = new[] { "page", "size", "search" }, VaryByHeader = HeaderNames.Cookie)]
+        [Authority, HttpPost, ResponseCache(Duration = 600, VaryByQueryKeys = new[] { "page", "size", "search" }, VaryByHeader = "Cookie")]
         public ActionResult SearchList(int page = 1, int size = 10, string search = "")
         {
             var where = string.IsNullOrEmpty(search) ? (Expression<Func<SearchDetails, bool>>)(s => true) : s => s.KeyWords.Contains(search);
@@ -109,7 +109,7 @@ namespace Masuit.MyBlogs.Core.Controllers
         /// 热词
         /// </summary>
         /// <returns></returns>
-        [Authority, HttpPost, ResponseCache(Duration = 600, VaryByHeader = HeaderNames.Cookie)]
+        [Authority, HttpPost, ResponseCache(Duration = 600, VaryByHeader = "Cookie")]
         public ActionResult HotKey()
         {
             return ResultData(new

+ 1 - 1
src/Masuit.MyBlogs.Core/Controllers/SeminarController.cs

@@ -38,7 +38,7 @@ namespace Masuit.MyBlogs.Core.Controllers
         /// <param name="size"></param>
         /// <param name="orderBy"></param>
         /// <returns></returns>
-        [Route("c/{id:int}/{page:int?}/{size:int?}"), ResponseCache(Duration = 600, VaryByQueryKeys = new[] { "id", "page", "size", "orderBy" }, VaryByHeader = HeaderNames.Cookie)]
+        [Route("c/{id:int}/{page:int?}/{size:int?}"), ResponseCache(Duration = 600, VaryByQueryKeys = new[] { "id", "page", "size", "orderBy" }, VaryByHeader = "Cookie")]
         public ActionResult Index(int id, [Optional]OrderBy? orderBy, int page = 1, int size = 15)
         {
             IList<Post> posts;

+ 2 - 2
src/Masuit.MyBlogs.Core/Controllers/SubscribeController.cs

@@ -37,7 +37,7 @@ namespace Masuit.MyBlogs.Core.Controllers
         /// </summary>
         public IPostService PostService { get; set; }
 
-        public IHostingEnvironment HostingEnvironment { get; set; }
+        public IWebHostEnvironment HostEnvironment { get; set; }
 
         /// <summary>
         /// 响应数据
@@ -146,7 +146,7 @@ namespace Masuit.MyBlogs.Core.Controllers
                     timespan = ts,
                     hash = (email + "verify" + guid + ts).AESEncrypt(AppConfig.BaiduAK)
                 }, "http");
-                BackgroundJob.Enqueue(() => CommonHelper.SendMail(CommonHelper.SystemSettings["Title"] + "博客订阅:" + Request.Host, System.IO.File.ReadAllText(HostingEnvironment.WebRootPath + "/template/subscribe.html").Replace("{{link}}", link), email));
+                BackgroundJob.Enqueue(() => CommonHelper.SendMail(CommonHelper.SystemSettings["Title"] + "博客订阅:" + Request.Host, System.IO.File.ReadAllText(HostEnvironment.WebRootPath + "/template/subscribe.html").Replace("{{link}}", link), email));
                 BroadcastService.SaveChanges();
                 return ResultData(null, message: "订阅成功,请打开您的邮箱确认操作后便可收到订阅更新!");
             }

+ 0 - 1
src/Masuit.MyBlogs.Core/Controllers/SystemController.cs

@@ -52,7 +52,6 @@ namespace Masuit.MyBlogs.Core.Controllers
             IList<string> ips = SystemInfo.GetIPAddress();
             var span = DateTime.Now - CommonHelper.StartupTime;
             var boot = DateTime.Now - SystemInfo.BootTime();
-
             return Json(new
             {
                 runningTime = $"{span.Days}天{span.Hours}小时{span.Minutes}分钟",

+ 3 - 3
src/Masuit.MyBlogs.Core/Controllers/ToolsController.cs

@@ -25,7 +25,7 @@ namespace Masuit.MyBlogs.Core.Controllers
         /// </summary>
         /// <param name="ip"></param>
         /// <returns></returns>
-        [HttpGet, Route("ip/{ip?}"), ResponseCache(Duration = 600, VaryByQueryKeys = new[] { "ip" }, VaryByHeader = HeaderNames.Cookie)]
+        [HttpGet, Route("ip/{ip?}"), ResponseCache(Duration = 600, VaryByQueryKeys = new[] { "ip" }, VaryByHeader = "Cookie")]
         public async Task<ActionResult> GetIpInfo(string ip)
         {
             if (string.IsNullOrEmpty(ip))
@@ -47,7 +47,7 @@ namespace Masuit.MyBlogs.Core.Controllers
         /// <param name="lat"></param>
         /// <param name="lng"></param>
         /// <returns></returns>
-        [HttpGet, Route("pos"), ResponseCache(Duration = 600, VaryByQueryKeys = new[] { "lat", "lng" }, VaryByHeader = HeaderNames.Cookie)]
+        [HttpGet, Route("pos"), ResponseCache(Duration = 600, VaryByQueryKeys = new[] { "lat", "lng" }, VaryByHeader = "Cookie")]
         public async Task<ActionResult> Position(string lat, string lng)
         {
             if (string.IsNullOrEmpty(lat) || string.IsNullOrEmpty(lng))
@@ -76,7 +76,7 @@ namespace Masuit.MyBlogs.Core.Controllers
         /// </summary>
         /// <param name="addr"></param>
         /// <returns></returns>
-        [HttpGet, Route("addr"), ResponseCache(Duration = 600, VaryByQueryKeys = new[] { "addr" }, VaryByHeader = HeaderNames.Cookie)]
+        [HttpGet, Route("addr"), ResponseCache(Duration = 600, VaryByQueryKeys = new[] { "addr" }, VaryByHeader = "Cookie")]
         public async Task<ActionResult> Address(string addr)
         {
             if (string.IsNullOrEmpty(addr))

+ 9 - 9
src/Masuit.MyBlogs.Core/Controllers/UploadController.cs

@@ -28,14 +28,14 @@ namespace Masuit.MyBlogs.Core.Controllers
     [ApiExplorerSettings(IgnoreApi = true)]
     public class UploadController : Controller
     {
-        public IHostingEnvironment HostingEnvironment { get; set; }
+        public IWebHostEnvironment HostEnvironment { get; set; }
 
         private readonly ImagebedClient _imagebedClient;
 
         /// <summary>
         /// 文件上传
         /// </summary>
-        /// <param name="hostingEnvironment"></param>
+        /// <param name="HostEnvironment"></param>
         public UploadController(ImagebedClient imagebedClient)
         {
             _imagebedClient = imagebedClient;
@@ -87,7 +87,7 @@ namespace Masuit.MyBlogs.Core.Controllers
                 return ResultData(null, false, "文件格式不支持,只能上传doc或者docx的文档!");
             }
 
-            string upload = HostingEnvironment.WebRootPath + "/upload";
+            string upload = HostEnvironment.WebRootPath + "/upload";
             if (!Directory.Exists(upload))
             {
                 Directory.CreateDirectory(upload);
@@ -139,7 +139,7 @@ namespace Masuit.MyBlogs.Core.Controllers
         public ActionResult Download(string path)
         {
             if (string.IsNullOrEmpty(path)) return Content("null");
-            var file = Path.Combine(HostingEnvironment.WebRootPath + "/upload", path.Trim('.', '/', '\\'));
+            var file = Path.Combine(HostEnvironment.WebRootPath + "/upload", path.Trim('.', '/', '\\'));
             if (System.IO.File.Exists(file))
             {
                 return this.ResumePhysicalFile(file, Path.GetFileName(file));
@@ -241,7 +241,7 @@ namespace Masuit.MyBlogs.Core.Controllers
                         return ResultData(url);
                     }
 
-                    path = Path.Combine(HostingEnvironment.WebRootPath, "upload", "images", filename);
+                    path = Path.Combine(HostEnvironment.WebRootPath, "upload", "images", filename);
                     var dir = Path.GetDirectoryName(path);
                     if (!Directory.Exists(dir))
                     {
@@ -255,13 +255,13 @@ namespace Masuit.MyBlogs.Core.Controllers
 
                     break;
                 case var _ when file.ContentType.StartsWith("audio") || file.ContentType.StartsWith("video"):
-                    path = Path.Combine(HostingEnvironment.WebRootPath, "upload", "media", filename);
+                    path = Path.Combine(HostEnvironment.WebRootPath, "upload", "media", filename);
                     break;
                 case var _ when file.ContentType.StartsWith("text") || (ContentType.Doc + "," + ContentType.Xls + "," + ContentType.Ppt + "," + ContentType.Pdf).Contains(file.ContentType):
-                    path = Path.Combine(HostingEnvironment.WebRootPath, "upload", "docs", filename);
+                    path = Path.Combine(HostEnvironment.WebRootPath, "upload", "docs", filename);
                     break;
                 default:
-                    path = Path.Combine(HostingEnvironment.WebRootPath, "upload", "files", filename);
+                    path = Path.Combine(HostEnvironment.WebRootPath, "upload", "files", filename);
                     break;
             }
             try
@@ -277,7 +277,7 @@ namespace Masuit.MyBlogs.Core.Controllers
                     file.CopyTo(fs);
                 }
 
-                return ResultData(path.Substring(HostingEnvironment.WebRootPath.Length).Replace("\\", "/"));
+                return ResultData(path.Substring(HostEnvironment.WebRootPath.Length).Replace("\\", "/"));
             }
             catch (Exception e)
             {

+ 2 - 1
src/Masuit.MyBlogs.Core/Extensions/AuthorityAttribute.cs

@@ -8,6 +8,7 @@ using Microsoft.AspNetCore.Authorization;
 using Microsoft.AspNetCore.Http;
 using Microsoft.AspNetCore.Mvc;
 using Microsoft.AspNetCore.Mvc.Filters;
+using Microsoft.Extensions.DependencyInjection;
 using System;
 using System.Linq;
 using System.Web;
@@ -40,7 +41,7 @@ namespace Masuit.MyBlogs.Core.Extensions
                 string name = filterContext.HttpContext.Request.Cookies["username"] ?? "";
                 string pwd = filterContext.HttpContext.Request.Cookies["password"]?.DesDecrypt(AppConfig.BaiduAK) ?? "";
 
-                var userInfo = (Startup.AutofacContainer.GetService(typeof(IUserInfoService)) as IUserInfoService).Login(name, pwd);
+                var userInfo = (Startup.ServiceProvider.GetRequiredService<IUserInfoService>()).Login(name, pwd);
                 if (userInfo != null)
                 {
                     filterContext.HttpContext.Response.Cookies.Append("username", name, new CookieOptions() { Expires = DateTime.Now.AddDays(7) });

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

@@ -30,7 +30,7 @@ namespace Masuit.MyBlogs.Core.Extensions.Hangfire
         private readonly ISearchDetailsService _searchDetailsService;
         private readonly ILinksService _linksService;
         private readonly IHttpClientFactory _httpClientFactory;
-        private readonly IHostingEnvironment _hostingEnvironment;
+        private readonly IWebHostEnvironment _HostEnvironment;
         private readonly ISearchEngine<DataContext> _searchEngine;
 
         /// <summary>
@@ -42,9 +42,9 @@ namespace Masuit.MyBlogs.Core.Extensions.Hangfire
         /// <param name="searchDetailsService"></param>
         /// <param name="linksService"></param>
         /// <param name="httpClientFactory"></param>
-        /// <param name="hostingEnvironment"></param>
+        /// <param name="HostEnvironment"></param>
         /// <param name="searchEngine"></param>
-        public HangfireBackJob(IUserInfoService userInfoService, IPostService postService, ISystemSettingService settingService, ISearchDetailsService searchDetailsService, ILinksService linksService, IHttpClientFactory httpClientFactory, IHostingEnvironment hostingEnvironment, ISearchEngine<DataContext> searchEngine)
+        public HangfireBackJob(IUserInfoService userInfoService, IPostService postService, ISystemSettingService settingService, ISearchDetailsService searchDetailsService, ILinksService linksService, IHttpClientFactory httpClientFactory, IWebHostEnvironment HostEnvironment, ISearchEngine<DataContext> searchEngine)
         {
             _userInfoService = userInfoService;
             _postService = postService;
@@ -52,7 +52,7 @@ namespace Masuit.MyBlogs.Core.Extensions.Hangfire
             _searchDetailsService = searchDetailsService;
             _linksService = linksService;
             _httpClientFactory = httpClientFactory;
-            _hostingEnvironment = hostingEnvironment;
+            _HostEnvironment = HostEnvironment;
             _searchEngine = searchEngine;
         }
 
@@ -83,7 +83,7 @@ namespace Masuit.MyBlogs.Core.Extensions.Hangfire
             var u = _userInfoService.GetByUsername(userInfo.Username);
             u.LoginRecord.Add(record);
             _userInfoService.SaveChanges();
-            var content = File.ReadAllText(Path.Combine(_hostingEnvironment.WebRootPath, "template", "login.html"))
+            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)

+ 108 - 0
src/Masuit.MyBlogs.Core/Extensions/MiddlewareExtension.cs

@@ -0,0 +1,108 @@
+using AutoMapper;
+using CacheManager.Core;
+using EFSecondLevelCache.Core;
+using Masuit.MyBlogs.Core.Configs;
+using Microsoft.AspNetCore.Builder;
+using Microsoft.AspNetCore.ResponseCompression;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.WebEncoders;
+using Newtonsoft.Json;
+using Newtonsoft.Json.Serialization;
+using System;
+using System.IO.Compression;
+using System.Linq;
+using System.Reflection;
+using System.Text.Encodings.Web;
+using System.Text.Unicode;
+
+namespace Masuit.MyBlogs.Core.Extensions
+{
+    public static class MiddlewareExtension
+    {
+        /// <summary>
+        /// 缓存配置
+        /// </summary>
+        /// <param name="services"></param>
+        /// <returns></returns>
+        public static IServiceCollection AddCacheConfig(this IServiceCollection services)
+        {
+            //配置EF二级缓存
+            services.AddEFSecondLevelCache();
+            // 配置EF二级缓存策略
+            services.AddSingleton(typeof(ICacheManager<>), typeof(BaseCacheManager<>));
+            services.AddSingleton(new CacheManager.Core.ConfigurationBuilder().WithJsonSerializer().WithMicrosoftMemoryCacheHandle().WithExpiration(ExpirationMode.Absolute, TimeSpan.FromMinutes(10)).Build());
+            return services;
+        }
+
+        /// <summary>
+        /// automapper
+        /// </summary>
+        /// <param name="services"></param>
+        /// <returns></returns>
+        public static IServiceCollection AddMapper(this IServiceCollection services)
+        {
+            var mc = new MapperConfiguration(e => e.AddProfile(new MappingProfile()));
+            services.AddAutoMapper(Assembly.GetExecutingAssembly());
+            services.AddSingleton(mc);
+            return services;
+        }
+
+        /// <summary>
+        /// mvc
+        /// </summary>
+        /// <param name="services"></param>
+        /// <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 =>
+            {
+                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);
+            }); //解决razor视图中中文被编码的问题
+            return services;
+        }
+
+        /// <summary>
+        /// 输出缓存
+        /// </summary>
+        /// <param name="services"></param>
+        /// <returns></returns>
+        public static IServiceCollection AddResponseCache(this IServiceCollection services)
+        {
+            services.AddResponseCaching(); //注入响应缓存
+            services.Configure<BrotliCompressionProviderOptions>(options =>
+            {
+                options.Level = CompressionLevel.Optimal;
+            }).Configure<GzipCompressionProviderOptions>(options =>
+            {
+                options.Level = CompressionLevel.Optimal;
+            }).AddResponseCompression(options =>
+            {
+                options.EnableForHttps = true;
+                options.Providers.Add<BrotliCompressionProvider>();
+                options.Providers.Add<GzipCompressionProvider>();
+                options.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(new[]
+                {
+                    "text/html; charset=utf-8",
+                    "application/xhtml+xml",
+                    "application/atom+xml",
+                    "image/svg+xml"
+                });
+            });
+            return services;
+        }
+    }
+}

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

@@ -76,7 +76,7 @@ namespace Masuit.MyBlogs.Core.Extensions.UEditor
                 using (var stream = response.Content.ReadAsStreamAsync().Result)
                 {
                     var savePath = AppContext.BaseDirectory + "wwwroot" + ServerUrl;
-                    var (url, success) = Startup.AutofacContainer.GetRequiredService<ImagebedClient>().UploadImage(stream, savePath).Result;
+                    var (url, success) = Startup.ServiceProvider.GetRequiredService<ImagebedClient>().UploadImage(stream, savePath).Result;
                     if (success)
                     {
                         ServerUrl = url;

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

@@ -49,7 +49,7 @@ namespace Masuit.MyBlogs.Core.Extensions.UEditor
                 {
                     using (Stream stream = file.OpenReadStream())
                     {
-                        var (url, success) = Startup.AutofacContainer.GetRequiredService<ImagebedClient>().UploadImage(stream, localPath).Result;
+                        var (url, success) = Startup.ServiceProvider.GetRequiredService<ImagebedClient>().UploadImage(stream, localPath).Result;
                         if (success)
                         {
                             Result.Url = url;

+ 12 - 10
src/Masuit.MyBlogs.Core/Masuit.MyBlogs.Core.csproj

@@ -1,12 +1,14 @@
 <Project Sdk="Microsoft.NET.Sdk.Web">
 
   <PropertyGroup>
-    <TargetFramework>netcoreapp2.2</TargetFramework>
+    <TargetFramework>netcoreapp3.0</TargetFramework>
     <AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
 	<ServerGarbageCollection>true</ServerGarbageCollection>
     <ConcurrentGarbageCollection>true</ConcurrentGarbageCollection>
     <Authors>懒得勤快</Authors>
     <Company>masuit.com</Company>
+    <RunAnalyzersDuringBuild>false</RunAnalyzersDuringBuild>
+    <RunAnalyzersDuringLiveAnalysis>false</RunAnalyzersDuringLiveAnalysis>
   </PropertyGroup>
 
   <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
@@ -50,8 +52,8 @@
     <PackageReference Include="Aspose.Words" Version="19.6.0" />
     <PackageReference Include="Autofac.Extensions.DependencyInjection" Version="5.0.1" />
     <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="7.0.0" />
-    <PackageReference Include="CacheManager.Microsoft.Extensions.Caching.Memory" Version="1.2.0" />
-    <PackageReference Include="CacheManager.Serialization.Json" Version="1.2.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="EFSecondLevelCache.Core" Version="2.8.1" />
     <PackageReference Include="Hangfire" Version="1.7.6" />
@@ -60,15 +62,15 @@
     <PackageReference Include="Hangfire.Redis.StackExchange" Version="1.8.0" />
     <PackageReference Include="htmldiff.net-core" Version="1.3.6" />
     <PackageReference Include="IP2Region" Version="1.2.0" />
-    <PackageReference Include="Microsoft.AspNetCore.App" />
-    <PackageReference Include="Microsoft.EntityFrameworkCore.Proxies" Version="2.2.6" />
-    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.2.3" />
+    <PackageReference Include="Microsoft.AspNetCore.Mvc.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" />
-    <PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="2.2.0" />
-    <PackageReference Include="WilderMinds.RssSyndication" Version="1.5.0" />
-    <PackageReference Include="Z.EntityFramework.Extensions.EFCore" Version="2.7.2" />
-    <PackageReference Include="Z.EntityFramework.Plus.EFCore" Version="2.0.8" />
+    <PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="3.0.0-rc1.final" />
+    <PackageReference Include="WilderMinds.RssSyndication" Version="1.6.0" />
+    <PackageReference Include="WinInsider.System.Net.Http.Formatting" Version="1.0.5" />
+    <PackageReference Include="Z.EntityFramework.Extensions.EFCore" Version="3.0.9" />
+    <PackageReference Include="Z.EntityFramework.Plus.EFCore" Version="3.0.14" />
     <PackageReference Include="Z.ExtensionMethods" Version="2.1.1" />
   </ItemGroup>
 

+ 17 - 12
src/Masuit.MyBlogs.Core/Program.cs

@@ -1,7 +1,8 @@
-using Masuit.MyBlogs.Core.Hubs;
-using Microsoft.AspNetCore;
+using Autofac.Extensions.DependencyInjection;
+using Masuit.MyBlogs.Core.Hubs;
 using Microsoft.AspNetCore.Hosting;
 using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.Hosting;
 using System;
 using System.IO;
 using Z.EntityFramework.Extensions;
@@ -17,24 +18,28 @@ namespace Masuit.MyBlogs.Core
             CreateWebHostBuilder(args).Build().Run();
         }
 
-        public static IWebHostBuilder CreateWebHostBuilder(string[] args)
+        public static IHostBuilder CreateWebHostBuilder(string[] args)
         {
             var builder = new ConfigurationBuilder().AddCommandLine(args).SetBasePath(Directory.GetCurrentDirectory()).AddEnvironmentVariables().AddJsonFile("appsettings.json", true, true);
             var config = builder.Build();
             var port = config["port"] ?? Environment.GetEnvironmentVariable("port") ?? "5000";
             var sslport = config["sslport"] ?? Environment.GetEnvironmentVariable("sslport") ?? "5001";
-            return WebHost.CreateDefaultBuilder(args).UseKestrel(opt =>
+            return Host.CreateDefaultBuilder(args).UseServiceProviderFactory(new AutofacServiceProviderFactory()).ConfigureWebHostDefaults(configurationBuilder =>
             {
-                opt.ListenAnyIP(port.ToInt32());
-                if (bool.Parse(config["Https:Enabled"]))
+                configurationBuilder.UseKestrel(opt =>
                 {
-                    opt.ListenAnyIP(sslport.ToInt32(), s =>
+                    opt.ListenAnyIP(port.ToInt32());
+                    if (bool.Parse(config["Https:Enabled"]))
                     {
-                        s.UseHttps(AppContext.BaseDirectory + config["Https:CertPath"], config["Https:CertPassword"]);
-                    });
-                }
-                opt.Limits.MaxRequestBodySize = null;
-            }).UseIISIntegration().UseStartup<Startup>();
+                        opt.ListenAnyIP(sslport.ToInt32(), s =>
+                        {
+                            s.UseHttps(AppContext.BaseDirectory + config["Https:CertPath"], config["Https:CertPassword"]);
+                        });
+                    }
+
+                    opt.Limits.MaxRequestBodySize = null;
+                }).UseIISIntegration().UseStartup<Startup>();
+            });
         }
     }
 }

+ 21 - 81
src/Masuit.MyBlogs.Core/Startup.cs

@@ -1,9 +1,6 @@
 using Autofac;
 using Autofac.Extensions.DependencyInjection;
-using AutoMapper;
-using CacheManager.Core;
 using CSRedis;
-using EFSecondLevelCache.Core;
 using Hangfire;
 using Hangfire.Dashboard;
 using Hangfire.MemoryStorage;
@@ -26,26 +23,19 @@ using Microsoft.AspNetCore.Builder;
 using Microsoft.AspNetCore.Hosting;
 using Microsoft.AspNetCore.Http;
 using Microsoft.AspNetCore.Http.Features;
-using Microsoft.AspNetCore.Mvc;
-using Microsoft.AspNetCore.ResponseCompression;
 using Microsoft.AspNetCore.Rewrite;
 using Microsoft.AspNetCore.StaticFiles;
 using Microsoft.AspNetCore.WebSockets;
 using Microsoft.EntityFrameworkCore;
 using Microsoft.Extensions.Configuration;
 using Microsoft.Extensions.DependencyInjection;
-using Microsoft.Extensions.WebEncoders;
+using Microsoft.Extensions.Hosting;
 using Microsoft.Net.Http.Headers;
-using Newtonsoft.Json;
-using Newtonsoft.Json.Serialization;
 using System;
 using System.IO;
-using System.IO.Compression;
 using System.Linq;
-using System.Reflection;
-using System.Text.Encodings.Web;
-using System.Text.Unicode;
 using System.Threading.Tasks;
+using IWebHostEnvironment = Microsoft.AspNetCore.Hosting.IWebHostEnvironment;
 using SameSiteMode = Microsoft.AspNetCore.Http.SameSiteMode;
 
 namespace Masuit.MyBlogs.Core
@@ -58,7 +48,7 @@ namespace Masuit.MyBlogs.Core
         /// <summary>
         /// 依赖注入容器
         /// </summary>
-        public static IServiceProvider AutofacContainer { get; set; }
+        public static IServiceProvider ServiceProvider { get; private set; }
 
         /// <summary>
         /// 配置中心
@@ -85,7 +75,7 @@ namespace Masuit.MyBlogs.Core
         /// </summary>
         /// <param name="services"></param>
         /// <returns></returns>
-        public IServiceProvider ConfigureServices(IServiceCollection services)
+        public void ConfigureServices(IServiceCollection services)
         {
             RedisHelper.Initialization(new CSRedisClient(AppConfig.Redis));
             services.Configure<CookiePolicyOptions>(options =>
@@ -97,7 +87,7 @@ namespace Masuit.MyBlogs.Core
                 opt.UseMySql(AppConfig.ConnString);
                 //opt.UseSqlServer(AppConfig.ConnString);
             }); //配置数据库
-            services.AddCors(opt => opt.AddDefaultPolicy(p => p.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().AllowCredentials())); //配置跨域
+            services.AddCors(opt => opt.AddDefaultPolicy(p => p.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin())); //配置跨域
             services.Configure<FormOptions>(options =>
             {
                 options.MultipartBodyLengthLimit = 104857600; // 100MB
@@ -109,15 +99,9 @@ namespace Masuit.MyBlogs.Core
                 options.RedirectStatusCode = StatusCodes.Status301MovedPermanently;
             });
 
-            ConfigureResponse(services);
-
+            services.AddResponseCache().AddCacheConfig();
             services.AddHangfire(x => x.UseMemoryStorage()); //配置hangfire
 
-            //配置EF二级缓存
-            services.AddEFSecondLevelCache();
-            // 配置EF二级缓存策略
-            services.AddSingleton(typeof(ICacheManager<>), typeof(BaseCacheManager<>));
-            services.AddSingleton(new CacheManager.Core.ConfigurationBuilder().WithJsonSerializer().WithMicrosoftMemoryCacheHandle().WithExpiration(ExpirationMode.Absolute, TimeSpan.FromMinutes(10)).Build());
             services.AddSevenZipCompressor().AddResumeFileResult().AddSearchEngine<DataContext>(new LuceneIndexerOptions()
             {
                 Path = "lucene"
@@ -127,62 +111,12 @@ namespace Masuit.MyBlogs.Core
             services.AddTransient<ImagebedClient>();
             services.AddHttpContextAccessor(); //注入静态HttpContext
 
-            services.AddMvc(options =>
-            {
-                options.Filters.Add<MyExceptionFilter>();
-                options.CacheProfiles.Add("Default", new CacheProfile()
-                {
-                    Location = ResponseCacheLocation.Any,
-                    VaryByHeader = HeaderNames.Cookie,
-                    Duration = 600
-                });
-            }).AddJsonOptions(opt =>
-            {
-                opt.SerializerSettings.ContractResolver = new DefaultContractResolver();
-                opt.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
-            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2).AddControllersAsServices().AddViewComponentsAsServices().AddTagHelpersAsServices();
-
-            services.Configure<WebEncoderOptions>(options =>
-            {
-                options.TextEncoderSettings = new TextEncoderSettings(UnicodeRanges.All);
-            }); //解决razor视图中中文被编码的问题
-
-            var mc = new MapperConfiguration(e => e.AddProfile(new MappingProfile()));
-            services.AddAutoMapper(Assembly.GetExecutingAssembly());
-            services.AddSingleton(mc);
-            services.AddAutofac();
-            ContainerBuilder builder = new ContainerBuilder();
-            builder.Populate(services);
-            builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).AsImplementedInterfaces().Where(t => t.Name.EndsWith("Repository") || t.Name.EndsWith("Service") || t.Name.EndsWith("Controller") || t.Name.EndsWith("Attribute")).PropertiesAutowired().AsSelf().InstancePerDependency(); //注册控制器为属性注入
-            builder.RegisterType<BackgroundJobClient>().SingleInstance(); //指定生命周期为单例
-            builder.RegisterType<FirewallAttribute>().PropertiesAutowired().AsSelf().InstancePerDependency(); //指定生命周期为单例
-            builder.RegisterType<HangfireBackJob>().As<IHangfireBackJob>().PropertiesAutowired(PropertyWiringOptions.PreserveSetValues).InstancePerDependency();
-            AutofacContainer = new AutofacServiceProvider(builder.Build());
-            return AutofacContainer;
+            services.AddMapper().AddAutofac().AddMyMvc();
         }
 
-        private static void ConfigureResponse(IServiceCollection services)
+        public void ConfigureContainer(ContainerBuilder builder)
         {
-            services.AddResponseCaching(); //注入响应缓存
-            services.Configure<BrotliCompressionProviderOptions>(options =>
-            {
-                options.Level = CompressionLevel.Optimal;
-            }).Configure<GzipCompressionProviderOptions>(options =>
-            {
-                options.Level = CompressionLevel.Optimal;
-            }).AddResponseCompression(options =>
-            {
-                options.EnableForHttps = true;
-                options.Providers.Add<BrotliCompressionProvider>();
-                options.Providers.Add<GzipCompressionProvider>();
-                options.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(new[]
-                {
-                    "text/html; charset=utf-8",
-                    "application/xhtml+xml",
-                    "application/atom+xml",
-                    "image/svg+xml"
-                });
-            });
+            builder.RegisterModule(new AutofacModule());
         }
 
         /// <summary>
@@ -193,8 +127,9 @@ namespace Masuit.MyBlogs.Core
         /// <param name="db"></param>
         /// <param name="hangfire"></param>
         /// <param name="luceneIndexerOptions"></param>
-        public void Configure(IApplicationBuilder app, IHostingEnvironment env, DataContext db, IHangfireBackJob hangfire, LuceneIndexerOptions luceneIndexerOptions)
+        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, DataContext db, IHangfireBackJob hangfire, LuceneIndexerOptions luceneIndexerOptions)
         {
+            ServiceProvider = app.ApplicationServices;
             if (env.IsDevelopment())
             {
                 app.UseDeveloperExceptionPage();
@@ -206,7 +141,7 @@ namespace Masuit.MyBlogs.Core
 
             //db.Database.Migrate();
 
-            ConfigureLuceneSearch(env, hangfire, luceneIndexerOptions);
+            UseLuceneSearch(env, hangfire, luceneIndexerOptions);
 
             app.UseResponseCompression();
             if (bool.Parse(Configuration["Https:Enabled"]))
@@ -241,14 +176,19 @@ namespace Masuit.MyBlogs.Core
                     new MyRestrictiveAuthorizationFilter()
                 }
             }); //配置hangfire
-            app.UseCors(builder => builder.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().AllowCredentials()); //配置跨域
+            app.UseCors(builder => builder.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin()); //配置跨域
             app.UseResponseCaching().UseResponseCompression(); //启动Response缓存
-            app.UseSignalR(hub => hub.MapHub<MyHub>("/hubs"));
             HangfireJobInit.Start(); //初始化定时任务
-            app.UseMvcWithDefaultRoute();
+            app.UseRouting(); // 放在 UseStaticFiles 之后
+            app.UseEndpoints(endpoints =>
+           {
+               endpoints.MapControllers(); // 属性路由
+               endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}"); // 默认路由
+               endpoints.MapHub<MyHub>("/hubs");
+           });
         }
 
-        private static void ConfigureLuceneSearch(IHostingEnvironment env, IHangfireBackJob hangfire, LuceneIndexerOptions luceneIndexerOptions)
+        private static void UseLuceneSearch(IWebHostEnvironment env, IHangfireBackJob hangfire, LuceneIndexerOptions luceneIndexerOptions)
         {
             Task.Run(() =>
             {

+ 2 - 2
src/Masuit.MyBlogs.Core/Views/Error/Index.cshtml

@@ -1,4 +1,4 @@
-@inject IHostingEnvironment HostingEnvironment
+@inject IWebHostEnvironment HostEnvironment
 @using System.IO
 @using AngleSharp.Network
 @using Masuit.Tools
@@ -95,7 +95,7 @@
             <div id="container">
                 @{
                     Random r = new Random();
-                    string imgPath = $"/Assets/images/404/404{r.StrictNext(Directory.GetFiles(HostingEnvironment.WebRootPath + "/Assets/images/404").Length) + 1}.jpg";
+                    string imgPath = $"/Assets/images/404/404{r.StrictNext(Directory.GetFiles(HostEnvironment.WebRootPath + "/Assets/images/404").Length) + 1}.jpg";
                 }
                 <img class="img img-responsive img-thumbnail" width="100%" src="@imgPath" alt="@ViewBag.Keywords" />
                 <h3 class="margintop20">

+ 2 - 2
src/Masuit.MyBlogs.Core/Views/Error/ServiceUnavailable.cshtml

@@ -1,4 +1,4 @@
-@inject IHostingEnvironment HostingEnvironment
+@inject IWebHostEnvironment HostEnvironment
 @using System.IO
 @using Masuit.Tools
 @using Masuit.Tools.Win32
@@ -96,7 +96,7 @@
         <div id="container">
             @{
                 Random r = new Random();
-                string imgPath = $"/Assets/images/503/503{r.StrictNext(Directory.GetFiles(HostingEnvironment.WebRootPath + "/Assets/images/503").Length) + 1}.jpg";
+                string imgPath = $"/Assets/images/503/503{r.StrictNext(Directory.GetFiles(HostEnvironment.WebRootPath + "/Assets/images/503").Length) + 1}.jpg";
             }
             <img class="img img-responsive img-thumbnail" width="100%" src="@imgPath" alt="@ViewBag.Keywords" />
             <h3 class="margintop20">