BaseController.cs 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. using Masuit.MyBlogs.Core.Configs;
  2. using Masuit.MyBlogs.Core.Infrastructure.Services.Interface;
  3. using Masuit.MyBlogs.Core.Models.DTO;
  4. using Masuit.MyBlogs.Core.Models.Enum;
  5. using Masuit.MyBlogs.Core.Models.ViewModel;
  6. using Masuit.Tools.Core.Net;
  7. using Masuit.Tools.NoSQL;
  8. using Masuit.Tools.Security;
  9. using Microsoft.AspNetCore.Http;
  10. using Microsoft.AspNetCore.Mvc;
  11. using Microsoft.AspNetCore.Mvc.Filters;
  12. using Newtonsoft.Json;
  13. using System;
  14. using System.Collections.Generic;
  15. using System.Linq;
  16. using System.Net;
  17. using System.Text;
  18. #if DEBUG
  19. using Common;
  20. #endif
  21. namespace Masuit.MyBlogs.Core.Controllers
  22. {
  23. /// <summary>
  24. /// 基本父控制器
  25. /// </summary>
  26. [ApiExplorerSettings(IgnoreApi = true)]
  27. public class BaseController : Controller
  28. {
  29. /// <summary>
  30. /// UserInfoService
  31. /// </summary>
  32. public IUserInfoService UserInfoService { get; set; }
  33. /// <summary>
  34. /// MenuService
  35. /// </summary>
  36. public IMenuService MenuService { get; set; }
  37. /// <summary>
  38. /// LinksService
  39. /// </summary>
  40. public ILinksService LinksService { get; set; }
  41. /// <summary>
  42. /// ContactsService
  43. /// </summary>
  44. public IContactsService ContactsService { get; set; }
  45. /// <summary>
  46. /// RedisHelper
  47. /// </summary>
  48. public RedisHelper RedisHelper { get; set; }
  49. /// <summary>
  50. /// 响应数据
  51. /// </summary>
  52. /// <param name="data">数据</param>
  53. /// <param name="success">响应状态</param>
  54. /// <param name="message">响应消息</param>
  55. /// <param name="isLogin">登录状态</param>
  56. /// <param name="code">http响应码</param>
  57. /// <returns></returns>
  58. public ContentResult ResultData(object data, bool success = true, string message = "", bool isLogin = true, HttpStatusCode code = HttpStatusCode.OK)
  59. {
  60. return Content(JsonConvert.SerializeObject(new
  61. {
  62. IsLogin = isLogin,
  63. Success = success,
  64. Message = message,
  65. Data = data,
  66. code
  67. }, new JsonSerializerSettings
  68. {
  69. MissingMemberHandling = MissingMemberHandling.Ignore,
  70. NullValueHandling = NullValueHandling.Ignore,
  71. ReferenceLoopHandling = ReferenceLoopHandling.Ignore
  72. }), "application/json", Encoding.UTF8);
  73. }
  74. /// <summary>
  75. /// 分页响应数据
  76. /// </summary>
  77. /// <param name="data">数据</param>
  78. /// <param name="pageCount">总页数</param>
  79. /// <param name="total">总条数</param>
  80. /// <returns></returns>
  81. public ContentResult PageResult(object data, int pageCount, int total)
  82. {
  83. return Content(JsonConvert.SerializeObject(new PageDataModel(data, pageCount, total), new JsonSerializerSettings
  84. {
  85. MissingMemberHandling = MissingMemberHandling.Ignore
  86. }), "application/json", Encoding.UTF8);
  87. }
  88. /// <summary>在调用操作方法前调用。</summary>
  89. /// <param name="filterContext">有关当前请求和操作的信息。</param>
  90. public override void OnActionExecuting(ActionExecutingContext filterContext)
  91. {
  92. base.OnActionExecuting(filterContext);
  93. if (filterContext.HttpContext.Request.Method.Equals("GET", StringComparison.InvariantCultureIgnoreCase)) //get方式的多半是页面
  94. {
  95. UserInfoOutputDto user = filterContext.HttpContext.Session.GetByRedis<UserInfoOutputDto>(SessionKey.UserInfo);
  96. #if DEBUG
  97. user = UserInfoService.GetByUsername("masuit").Mapper<UserInfoOutputDto>();
  98. filterContext.HttpContext.Session.SetByRedis(SessionKey.UserInfo, user);
  99. #endif
  100. if (user == null && Request.Cookies.Count > 2) //执行自动登录
  101. {
  102. string name = Request.Cookies["username"];
  103. string pwd = Request.Cookies["password"]?.DesDecrypt(AppConfig.BaiduAK);
  104. var userInfo = UserInfoService.Login(name, pwd);
  105. if (userInfo != null)
  106. {
  107. Response.Cookies.Append("username", name, new CookieOptions()
  108. {
  109. Expires = DateTime.Now.AddDays(7)
  110. });
  111. Response.Cookies.Append("password", Request.Cookies["password"].DesEncrypt(AppConfig.BaiduAK), new CookieOptions()
  112. {
  113. Expires = DateTime.Now.AddDays(7)
  114. });
  115. filterContext.HttpContext.Session.SetByRedis(SessionKey.UserInfo, userInfo);
  116. }
  117. }
  118. }
  119. else
  120. {
  121. if (ModelState.IsValid) return;
  122. List<string> errmsgs = new List<string>();
  123. ModelState.ForEach(kv => kv.Value.Errors.ForEach(error => errmsgs.Add(error.ErrorMessage)));
  124. if (errmsgs.Count > 1)
  125. {
  126. for (var i = 0; i < errmsgs.Count; i++)
  127. {
  128. errmsgs[i] = i + 1 + ". " + errmsgs[i];
  129. }
  130. }
  131. filterContext.Result = ResultData(errmsgs, false, "数据校验失败,错误信息:" + string.Join(" | ", errmsgs), true, HttpStatusCode.BadRequest);
  132. }
  133. }
  134. /// <summary>在调用操作方法后调用。</summary>
  135. /// <param name="filterContext">有关当前请求和操作的信息。</param>
  136. public override void OnActionExecuted(ActionExecutedContext filterContext)
  137. {
  138. base.OnActionExecuted(filterContext);
  139. if (filterContext.HttpContext.Request.Method.Equals("POST", StringComparison.InvariantCultureIgnoreCase) && filterContext.Result is ViewResult)
  140. {
  141. filterContext.Result = ResultData(null, false, "该URL仅支持Get请求方式", false, HttpStatusCode.MethodNotAllowed);
  142. return;
  143. }
  144. #region 准备页面数据模型
  145. ViewBag.menus = MenuService.LoadEntitiesFromL2Cache<MenuOutputDto>(m => m.Status == Status.Available).OrderBy(m => m.Sort).ToList(); //菜单
  146. PageFootViewModel model = new PageFootViewModel //页脚
  147. {
  148. Links = LinksService.LoadPageEntitiesFromL2Cache<bool, LinksOutputDto>(1, 40, out int _, l => l.Status == Status.Available, l => l.Recommend, false).ToList(),
  149. Contacts = ContactsService.LoadEntitiesFromL2Cache<int, ContactsOutputDto>(l => l.Status == Status.Available, l => l.Id, false).ToList()
  150. };
  151. ViewBag.Footer = model;
  152. #endregion
  153. }
  154. }
  155. }