From d09de26d6ea095c626bdfa623a23d91d1902aae8 Mon Sep 17 00:00:00 2001
From: hudingwen <765472804@qq.com>
Date: Sun, 12 Feb 2023 22:00:04 +0800
Subject: [PATCH 01/84] =?UTF-8?q?=E5=90=8C=E6=AD=A5=E4=B8=BB=E5=88=86?=
=?UTF-8?q?=E6=94=AF?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
Blog.Core.Api/Blog.Core.Model.xml | 137 ++++++
Blog.Core.Api/Blog.Core.xml | 160 +++++++
Blog.Core.Api/Controllers/TrojanController.cs | 451 ++++++++++++++++++
Blog.Core.Api/Controllers/WeChatController.cs | 12 +
Blog.Core.Api/Dockerfile | 2 +-
Blog.Core.IServices/BASE/IBaseServices.cs | 1 +
Blog.Core.IServices/ITrojanUsersServices.cs | 14 +
Blog.Core.Model/Models/TrojanCusServers.cs | 26 +
Blog.Core.Model/Models/TrojanDetails.cs | 63 +++
Blog.Core.Model/Models/TrojanServers.cs | 31 ++
Blog.Core.Model/Models/TrojanUrlServers.cs | 26 +
Blog.Core.Model/Models/TrojanUsers.cs | 39 ++
.../ViewModels/TrojanLimitFlowDto.cs | 23 +
Blog.Core.Model/ViewModels/TrojanServerDto.cs | 14 +
.../ViewModels/TrojanServerSpliceDto.cs | 28 ++
.../ViewModels/TrojanUseDetailDto.cs | 35 ++
Blog.Core.Repository/BASE/BaseRepository.cs | 13 +
Blog.Core.Repository/BASE/IBaseRepository.cs | 6 +
Blog.Core.Services/BASE/BaseServices.cs | 9 +
Blog.Core.Services/TrojanUsersServices.cs | 18 +
Blog.Core.Tasks/Blog.Core.Tasks.csproj | 1 +
.../HostedService/Job1TimedService.cs | 60 +++
.../HostedService/Job2TimedService.cs | 47 ++
.../QuartzNet/Jobs/Job_Trojan_Quartz.cs | 79 +++
.../QuartzNet/Jobs/Job_URL_Quartz.cs | 51 ++
25 files changed, 1345 insertions(+), 1 deletion(-)
create mode 100644 Blog.Core.Api/Controllers/TrojanController.cs
create mode 100644 Blog.Core.IServices/ITrojanUsersServices.cs
create mode 100644 Blog.Core.Model/Models/TrojanCusServers.cs
create mode 100644 Blog.Core.Model/Models/TrojanDetails.cs
create mode 100644 Blog.Core.Model/Models/TrojanServers.cs
create mode 100644 Blog.Core.Model/Models/TrojanUrlServers.cs
create mode 100644 Blog.Core.Model/Models/TrojanUsers.cs
create mode 100644 Blog.Core.Model/ViewModels/TrojanLimitFlowDto.cs
create mode 100644 Blog.Core.Model/ViewModels/TrojanServerDto.cs
create mode 100644 Blog.Core.Model/ViewModels/TrojanServerSpliceDto.cs
create mode 100644 Blog.Core.Model/ViewModels/TrojanUseDetailDto.cs
create mode 100644 Blog.Core.Services/TrojanUsersServices.cs
create mode 100644 Blog.Core.Tasks/HostedService/Job1TimedService.cs
create mode 100644 Blog.Core.Tasks/HostedService/Job2TimedService.cs
create mode 100644 Blog.Core.Tasks/QuartzNet/Jobs/Job_Trojan_Quartz.cs
create mode 100644 Blog.Core.Tasks/QuartzNet/Jobs/Job_URL_Quartz.cs
diff --git a/Blog.Core.Api/Blog.Core.Model.xml b/Blog.Core.Api/Blog.Core.Model.xml
index 36975d11..ea9857bc 100644
--- a/Blog.Core.Api/Blog.Core.Model.xml
+++ b/Blog.Core.Api/Blog.Core.Model.xml
@@ -982,6 +982,76 @@
Tibug 博文
+
+
+ users自定义服务器
+
+
+
+
+ 用户流量每月汇总表
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Trojan服务器
+
+
+
+
+ users自定义URL服务器
+
+
+
+
+ Trojan用户
+
+
+
+
+ 历史流量记录
+
+
用户跟角色关联表
@@ -2407,6 +2477,73 @@
+
+
+ 限制流量dto
+ 作者:胡丁文
+ 时间:2020-4-27 16:57:07
+
+
+
+
+ 用户
+
+
+
+
+ 流量(-1为无限,单位为最小单位byte)
+
+
+
+
+ Trojan服务器拼接服务器和订阅地址
+
+
+
+
+ 普通订阅连接
+
+
+
+
+ clash订阅连接
+
+
+
+
+ 备用clash订阅连接
+
+
+
+
+ Trojan用户流量统计分组
+
+
+
+
+ 用户ID
+
+
+
+
+ 月度
+
+
+
+
+ 上传流量
+
+
+
+
+ 下载流量
+
+
+
+
+ 下载流量
+
+
微信接口消息DTO
diff --git a/Blog.Core.Api/Blog.Core.xml b/Blog.Core.Api/Blog.Core.xml
index 3321d53a..a14a9006 100644
--- a/Blog.Core.Api/Blog.Core.xml
+++ b/Blog.Core.Api/Blog.Core.xml
@@ -650,6 +650,159 @@
+
+
+ 获取Trojan用户
+
+
+
+
+
+
+
+
+ 获取Trojan用户-下拉列表用
+
+
+
+
+
+ 添加Trojan用户
+
+
+
+
+
+
+ 更新Trojan用户
+
+
+
+
+
+
+ 删除用户
+
+
+
+
+
+
+ 重置流量
+
+
+
+
+
+
+ 限制流量
+
+
+
+
+
+
+ 重置链接密码
+
+
+
+
+
+
+ 获取Trojan服务器
+
+
+
+
+
+ 获取拼接后的Trojan服务器
+
+ passwordshow
+
+
+
+
+ 删除Trojan服务器
+
+
+
+
+
+
+ 更新Trojan服务器
+
+
+
+
+
+
+ 添加Trojan服务器
+
+
+
+
+
+
+ 获取Cus服务器
+
+
+
+
+
+ 删除Cus服务器
+
+
+
+
+
+
+ 更新Cus服务器
+
+
+
+
+
+
+ 添加Cus服务器
+
+
+
+
+
+
+ 获取Url服务器
+
+
+
+
+
+ 删除Url服务器
+
+
+
+
+
+
+ 更新Url服务器
+
+
+
+
+
+
+ 添加Url服务器
+
+
+
+
+
+
+ 获取订阅数据
+
+ 链接密码
+ 是否使用base64加密
+
+
用户管理
@@ -1062,6 +1215,13 @@
卡片消息对象
+
+
+ 推送卡片消息接口
+
+ 卡片消息对象
+
+
推送文本消息
diff --git a/Blog.Core.Api/Controllers/TrojanController.cs b/Blog.Core.Api/Controllers/TrojanController.cs
new file mode 100644
index 00000000..8ec64c8a
--- /dev/null
+++ b/Blog.Core.Api/Controllers/TrojanController.cs
@@ -0,0 +1,451 @@
+using System;
+using System.Collections.Generic;
+using System.Data;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using Blog.Core.Common;
+using Blog.Core.Common.Extensions;
+using Blog.Core.Common.Helper;
+using Blog.Core.Common.HttpContextUser;
+using Blog.Core.IServices;
+using Blog.Core.IServices.BASE;
+using Blog.Core.Model;
+using Blog.Core.Model.Models;
+using Blog.Core.Model.ViewModels;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Blog.Core.Controllers
+{
+ [Route("api/[controller]/[action]")]
+ [ApiController]
+ [Authorize(Permissions.Name)]
+ public class TrojanController : ControllerBase
+ {
+ private ITrojanUsersServices _trojanUsersServices;
+ public IBaseServices _baseServicesServers;
+ public IBaseServices _baseServicesDetails;
+ public IBaseServices _baseServicesCusServers;
+ public IBaseServices _baseServicesUrlServers;
+ private IUser _user;
+ public TrojanController(ITrojanUsersServices trojanUsersServices,IUser user
+ , IBaseServices baseServicesServers
+ , IBaseServices baseServicesDetails
+ , IBaseServices baseServicesCusServers
+ , IBaseServices baseServicesUrlServers)
+ {
+ _baseServicesDetails = baseServicesDetails;
+ _baseServicesServers = baseServicesServers;
+ _trojanUsersServices = trojanUsersServices;
+ _baseServicesCusServers = baseServicesCusServers;
+ _baseServicesUrlServers = baseServicesUrlServers;
+ _user = user;
+ }
+ ///
+ /// 获取Trojan用户
+ ///
+ ///
+ ///
+ ///
+ ///
+ [HttpGet]
+ public async Task>> GetUser([FromQuery]PaginationModel pagination, [FromQuery] string name, [FromQuery] bool isuse)
+ {
+ var whereFind = LinqHelper.True();
+ if (!string.IsNullOrEmpty(name))
+ whereFind = whereFind.And(t=>t.username.Contains(name));
+ if (isuse)
+ whereFind = whereFind.And(t => t.upload > 0 || t.download > 0);
+ var data = await _trojanUsersServices.QueryPage(whereFind, pagination.PageIndex, pagination.PageSize);
+ if (data.data.Count > 0)
+ {
+ var ids = data.data.Select(t => t.id).ToList();
+ var where = LinqHelper.True();
+ where = where.And(t => ids.Contains(t.userId));//.And(t => t.calDate < DateTime.Now).And(t => t.calDate > DateTime.Now.AddMonths(-12));
+ var userDetails = await _baseServicesDetails.Query(where);
+ foreach (var trojanUser in data.data)
+ {
+ var ls = from t in userDetails
+ where t.userId == trojanUser.id
+ group t by new { moth = t.calDate.ToString("yyyy-MM"), id = t.userId } into g
+ orderby g.Key.moth descending
+ select new TrojanUseDetailDto { userId = g.Key.id, moth = g.Key.moth, up = g.Sum(t => Convert.ToDecimal(t.upload)), down = g.Sum(t => Convert.ToDecimal(t.download)) };
+ var lsData = ls.ToList();
+ trojanUser.useList = lsData;
+ }
+ }
+ return MessageModel>.Success("获取成功", data);
+ }
+
+ ///
+ /// 获取Trojan用户-下拉列表用
+ ///
+ ///
+ [HttpGet]
+ public async Task> GetAllTrojanUser()
+ {
+ var data = await _trojanUsersServices.QueryTable("select id,username from users");
+ return MessageModel.Success("获取成功", data);
+ }
+ ///
+ /// 添加Trojan用户
+ ///
+ ///
+ ///
+ [HttpPost]
+ public async Task> AddUser([FromBody]TrojanUsers user)
+ {
+ var find = await _trojanUsersServices.Query(t => t.username == user.username);
+ if(find!=null && find.Count>0) return MessageModel
任务概况
-
-
-
diff --git a/Blog.Core.Api/Controllers/BlogController.cs b/Blog.Core.Api/Controllers/BlogController.cs
index 6525448e..83fad967 100644
--- a/Blog.Core.Api/Controllers/BlogController.cs
+++ b/Blog.Core.Api/Controllers/BlogController.cs
@@ -1,8 +1,5 @@
-using System;
-using System.Collections.Generic;
-using System.Linq.Expressions;
+using System.Linq.Expressions;
using System.Text.RegularExpressions;
-using System.Threading.Tasks;
using Blog.Core.Common.Helper;
using Blog.Core.IServices;
using Blog.Core.Model;
@@ -11,7 +8,6 @@
using Blog.Core.SwaggerHelper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
-using Microsoft.Extensions.Logging;
using StackExchange.Profiling;
using static Blog.Core.Extensions.CustomApiVersion;
diff --git a/Blog.Core.Api/Controllers/DepartmentController.cs b/Blog.Core.Api/Controllers/DepartmentController.cs
index 1674883f..bca7bf6d 100644
--- a/Blog.Core.Api/Controllers/DepartmentController.cs
+++ b/Blog.Core.Api/Controllers/DepartmentController.cs
@@ -4,17 +4,10 @@
using Blog.Core.Model;
using Blog.Core.Model.Models;
using Microsoft.AspNetCore.Authorization;
-using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
-using Microsoft.Extensions.Hosting;
using Newtonsoft.Json;
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
using System.Linq.Expressions;
using System.Text;
-using System.Threading.Tasks;
namespace Blog.Core.Api.Controllers
{
diff --git a/Blog.Core.Api/Controllers/ModuleController.cs b/Blog.Core.Api/Controllers/ModuleController.cs
index 334a8ea4..2da284ba 100644
--- a/Blog.Core.Api/Controllers/ModuleController.cs
+++ b/Blog.Core.Api/Controllers/ModuleController.cs
@@ -1,7 +1,4 @@
-using System;
-using System.Collections.Generic;
-using System.Linq.Expressions;
-using System.Threading.Tasks;
+using System.Linq.Expressions;
using Blog.Core.Common.HttpContextUser;
using Blog.Core.IServices;
using Blog.Core.Model;
diff --git a/Blog.Core.Api/Controllers/MonitorController.cs b/Blog.Core.Api/Controllers/MonitorController.cs
index c0dbed52..77b4e5bf 100644
--- a/Blog.Core.Api/Controllers/MonitorController.cs
+++ b/Blog.Core.Api/Controllers/MonitorController.cs
@@ -6,19 +6,12 @@
using Blog.Core.Model;
using Blog.Core.Model.ViewModels;
using Microsoft.AspNetCore.Authorization;
-using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
-using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
-using System;
-using System.Collections.Generic;
using System.Diagnostics;
-using System.IO;
-using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
-using System.Threading.Tasks;
using Blog.Core.Extensions.Middlewares;
namespace Blog.Core.Controllers
diff --git a/Blog.Core.Api/Controllers/NacosController.cs b/Blog.Core.Api/Controllers/NacosController.cs
index a8701b39..e5223851 100644
--- a/Blog.Core.Api/Controllers/NacosController.cs
+++ b/Blog.Core.Api/Controllers/NacosController.cs
@@ -4,7 +4,6 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Nacos.V2;
-using System.Threading.Tasks;
namespace Blog.Core.Api.Controllers
{
diff --git a/Blog.Core.Api/Controllers/PayController.cs b/Blog.Core.Api/Controllers/PayController.cs
index 0cbe0541..6c05c249 100644
--- a/Blog.Core.Api/Controllers/PayController.cs
+++ b/Blog.Core.Api/Controllers/PayController.cs
@@ -1,10 +1,8 @@
-using System.Threading.Tasks;
-using Blog.Core.IServices;
+using Blog.Core.IServices;
using Blog.Core.Model;
using Blog.Core.Model.ViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
-using Microsoft.Extensions.Logging;
namespace Blog.Core.Controllers
{
diff --git a/Blog.Core.Api/Controllers/RoleController.cs b/Blog.Core.Api/Controllers/RoleController.cs
index 36df73a4..c96502c8 100644
--- a/Blog.Core.Api/Controllers/RoleController.cs
+++ b/Blog.Core.Api/Controllers/RoleController.cs
@@ -1,5 +1,4 @@
-using System.Threading.Tasks;
-using Blog.Core.Common.HttpContextUser;
+using Blog.Core.Common.HttpContextUser;
using Blog.Core.IServices;
using Blog.Core.Model;
using Blog.Core.Model.Models;
diff --git a/Blog.Core.Api/Controllers/TasksQzController.cs b/Blog.Core.Api/Controllers/TasksQzController.cs
index e5c866c3..ca9d37bc 100644
--- a/Blog.Core.Api/Controllers/TasksQzController.cs
+++ b/Blog.Core.Api/Controllers/TasksQzController.cs
@@ -1,17 +1,10 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Linq.Expressions;
+using System.Linq.Expressions;
using System.Reflection;
-using System.Threading.Tasks;
-using Blog.Core.Common.Extensions;
-using Blog.Core.Common.WebApiClients.HttpApis;
using Blog.Core.IServices;
using Blog.Core.Model;
using Blog.Core.Model.Models;
using Blog.Core.Model.ViewModels;
using Blog.Core.Repository.UnitOfWorks;
-using Blog.Core.Services;
using Blog.Core.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
@@ -29,10 +22,10 @@ public class TasksQzController : ControllerBase
private readonly ISchedulerCenter _schedulerCenter;
private readonly IUnitOfWorkManage _unitOfWorkManage;
- public TasksQzController(ITasksQzServices tasksQzServices, ISchedulerCenter schedulerCenter, IUnitOfWorkManage unitOfWorkManage,ITasksLogServices tasksLogServices)
+ public TasksQzController(ITasksQzServices tasksQzServices, ISchedulerCenter schedulerCenter, IUnitOfWorkManage unitOfWorkManage, ITasksLogServices tasksLogServices)
{
_unitOfWorkManage = unitOfWorkManage;
- _tasksQzServices = tasksQzServices;
+ _tasksQzServices = tasksQzServices;
_schedulerCenter = schedulerCenter;
_tasksLogServices = tasksLogServices;
}
@@ -63,7 +56,7 @@ public async Task>> Get(int page = 1, string key
item.Triggers = await _schedulerCenter.GetTaskStaus(item);
}
}
- return MessageModel>.Message(data.dataCount >= 0, "获取成功", data);
+ return MessageModel>.Message(data.dataCount >= 0, "获取成功", data);
}
///
@@ -91,32 +84,33 @@ public async Task> Post([FromBody] TasksQz tasksQz)
var ResuleModel = await _schedulerCenter.AddScheduleJobAsync(tasksQz);
data.success = ResuleModel.success;
if (ResuleModel.success)
- {
+ {
data.msg = $"{data.msg}=>启动成功=>{ResuleModel.msg}";
}
else
- {
+ {
data.msg = $"{data.msg}=>启动失败=>{ResuleModel.msg}";
}
}
}
else
- {
+ {
data.msg = "添加失败";
- }
+ }
}
catch (Exception)
{
throw;
}
finally
- { if(data.success)
+ {
+ if (data.success)
_unitOfWorkManage.CommitTran();
else
_unitOfWorkManage.RollbackTran();
}
- return data;
+ return data;
}
@@ -140,7 +134,7 @@ public async Task> Put([FromBody] TasksQz tasksQz)
data.msg = "修改成功";
data.response = tasksQz?.Id.ObjToString();
if (tasksQz.IsStart)
- {
+ {
var ResuleModelStop = await _schedulerCenter.StopScheduleJobAsync(tasksQz);
data.msg = $"{data.msg}=>停止:{ResuleModelStop.msg}";
var ResuleModelStar = await _schedulerCenter.AddScheduleJobAsync(tasksQz);
@@ -168,7 +162,7 @@ public async Task> Put([FromBody] TasksQz tasksQz)
_unitOfWorkManage.CommitTran();
else
_unitOfWorkManage.RollbackTran();
- }
+ }
}
return data;
}
@@ -212,7 +206,7 @@ public async Task> Delete(int jobId)
_unitOfWorkManage.CommitTran();
else
_unitOfWorkManage.RollbackTran();
- }
+ }
}
else
{
@@ -234,7 +228,7 @@ public async Task> StartJob(int jobId)
var model = await _tasksQzServices.QueryById(jobId);
if (model != null)
{
- _unitOfWorkManage.BeginTran();
+ _unitOfWorkManage.BeginTran();
try
{
model.IsStart = true;
@@ -270,7 +264,7 @@ public async Task> StartJob(int jobId)
_unitOfWorkManage.CommitTran();
else
_unitOfWorkManage.RollbackTran();
- }
+ }
}
else
{
@@ -326,10 +320,10 @@ public async Task> StopJob(int jobId)
[HttpGet]
public async Task> PauseJob(int jobId)
{
- var data = new MessageModel();
+ var data = new MessageModel();
var model = await _tasksQzServices.QueryById(jobId);
if (model != null)
- {
+ {
_unitOfWorkManage.BeginTran();
try
{
@@ -364,7 +358,7 @@ public async Task> PauseJob(int jobId)
_unitOfWorkManage.CommitTran();
else
_unitOfWorkManage.RollbackTran();
- }
+ }
}
else
{
@@ -384,7 +378,7 @@ public async Task> ResumeJob(int jobId)
var model = await _tasksQzServices.QueryById(jobId);
if (model != null)
- {
+ {
_unitOfWorkManage.BeginTran();
try
{
@@ -420,7 +414,7 @@ public async Task> ResumeJob(int jobId)
_unitOfWorkManage.CommitTran();
else
_unitOfWorkManage.RollbackTran();
- }
+ }
}
else
{
@@ -480,7 +474,7 @@ public async Task> ReCovery(int jobId)
_unitOfWorkManage.CommitTran();
else
_unitOfWorkManage.RollbackTran();
- }
+ }
}
else
{
@@ -493,7 +487,7 @@ public async Task> ReCovery(int jobId)
/// 获取任务命名空间
///
///
- [HttpGet]
+ [HttpGet]
public MessageModel> GetTaskNameSpace()
{
var baseType = typeof(IJob);
@@ -506,7 +500,7 @@ public MessageModel> GetTaskNameSpace()
var implementTypes = types.Where(x => x.IsClass).Select(item => new QuartzReflectionViewModel { nameSpace = item.Namespace, nameClass = item.Name, remark = "" }).ToList();
return MessageModel>.Success("获取成功", implementTypes);
}
-
+
///
/// 立即执行任务
///
@@ -531,12 +525,9 @@ public async Task> ExecuteJob(int jobId)
///
/// 获取任务运行日志
///
- ///
- ///
- ///
///
[HttpGet]
- public async Task>> GetTaskLogs(int jobId, int page = 1, int pageSize = 10, DateTime? runTimeStart =null, DateTime? runTimeEnd = null)
+ public async Task>> GetTaskLogs(int jobId, int page = 1, int pageSize = 10, DateTime? runTimeStart = null, DateTime? runTimeEnd = null)
{
var model = await _tasksLogServices.GetTaskLogs(jobId, page, pageSize, runTimeStart, runTimeEnd);
return MessageModel>.Message(model.dataCount >= 0, "获取成功", model);
@@ -544,12 +535,9 @@ public async Task>> GetTaskLogs(int jobId, int
///
/// 任务概况
///
- ///
- ///
- ///
///
[HttpGet]
- public async Task> GetTaskOverview(int jobId, int page = 1, int pageSize = 10, DateTime? runTimeStart = null, DateTime? runTimeEnd = null, string type ="month")
+ public async Task> GetTaskOverview(int jobId, int page = 1, int pageSize = 10, DateTime? runTimeStart = null, DateTime? runTimeEnd = null, string type = "month")
{
var model = await _tasksLogServices.GetTaskOverview(jobId, runTimeStart, runTimeEnd, type);
return MessageModel.Message(true, "获取成功", model);
diff --git a/Blog.Core.Api/Controllers/TopicController.cs b/Blog.Core.Api/Controllers/TopicController.cs
index 1fe2d4a3..308ad082 100644
--- a/Blog.Core.Api/Controllers/TopicController.cs
+++ b/Blog.Core.Api/Controllers/TopicController.cs
@@ -1,6 +1,4 @@
-using System.Collections.Generic;
-using System.Threading.Tasks;
-using Blog.Core.IServices;
+using Blog.Core.IServices;
using Blog.Core.Model;
using Blog.Core.Model.Models;
using Microsoft.AspNetCore.Authorization;
diff --git a/Blog.Core.Api/Controllers/TopicDetailController.cs b/Blog.Core.Api/Controllers/TopicDetailController.cs
index 264fe2df..55af1a75 100644
--- a/Blog.Core.Api/Controllers/TopicDetailController.cs
+++ b/Blog.Core.Api/Controllers/TopicDetailController.cs
@@ -1,7 +1,4 @@
-using System;
-using System.Linq;
-using System.Threading.Tasks;
-using Blog.Core.Common.Helper;
+using Blog.Core.Common.Helper;
using Blog.Core.IServices;
using Blog.Core.Model;
using Blog.Core.Model.Models;
diff --git a/Blog.Core.Api/Controllers/TransactionController.cs b/Blog.Core.Api/Controllers/TransactionController.cs
index dd6b0384..67ab576e 100644
--- a/Blog.Core.Api/Controllers/TransactionController.cs
+++ b/Blog.Core.Api/Controllers/TransactionController.cs
@@ -1,7 +1,4 @@
-using System;
-using System.Collections.Generic;
-using System.Threading.Tasks;
-using Blog.Core.IServices;
+using Blog.Core.IServices;
using Blog.Core.Model;
using Blog.Core.Model.Models;
using Blog.Core.Repository.UnitOfWorks;
diff --git a/Blog.Core.Api/Controllers/UserController.cs b/Blog.Core.Api/Controllers/UserController.cs
index 6a2a18fa..43f7f610 100644
--- a/Blog.Core.Api/Controllers/UserController.cs
+++ b/Blog.Core.Api/Controllers/UserController.cs
@@ -1,8 +1,4 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading.Tasks;
-using AutoMapper;
+using AutoMapper;
using Blog.Core.AuthHelper.OverWrite;
using Blog.Core.Common.Helper;
using Blog.Core.Common.HttpContextUser;
@@ -13,7 +9,6 @@
using Blog.Core.Repository.UnitOfWorks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
-using Microsoft.Extensions.Logging;
namespace Blog.Core.Controllers
{
diff --git a/Blog.Core.Api/Controllers/UserRoleController.cs b/Blog.Core.Api/Controllers/UserRoleController.cs
index d14d6a73..c21ec6f4 100644
--- a/Blog.Core.Api/Controllers/UserRoleController.cs
+++ b/Blog.Core.Api/Controllers/UserRoleController.cs
@@ -1,5 +1,4 @@
-using System.Threading.Tasks;
-using AutoMapper;
+using AutoMapper;
using Blog.Core.IServices;
using Blog.Core.Model;
using Blog.Core.Model.Models;
diff --git a/Blog.Core.Api/Controllers/WeChatCompanyController.cs b/Blog.Core.Api/Controllers/WeChatCompanyController.cs
index 4fa6eea5..dc12930b 100644
--- a/Blog.Core.Api/Controllers/WeChatCompanyController.cs
+++ b/Blog.Core.Api/Controllers/WeChatCompanyController.cs
@@ -1,4 +1,3 @@
-using System.Threading.Tasks;
using Blog.Core.IServices;
using Blog.Core.Model;
using Blog.Core.Model.Models;
diff --git a/Blog.Core.Api/Controllers/WeChatConfigController.cs b/Blog.Core.Api/Controllers/WeChatConfigController.cs
index c597cb3f..1f3b705d 100644
--- a/Blog.Core.Api/Controllers/WeChatConfigController.cs
+++ b/Blog.Core.Api/Controllers/WeChatConfigController.cs
@@ -1,4 +1,3 @@
-using System.Threading.Tasks;
using Blog.Core.IServices;
using Blog.Core.Model;
using Blog.Core.Model.Models;
diff --git a/Blog.Core.Api/Controllers/WeChatController.cs b/Blog.Core.Api/Controllers/WeChatController.cs
index 4c4877f6..9927eb78 100644
--- a/Blog.Core.Api/Controllers/WeChatController.cs
+++ b/Blog.Core.Api/Controllers/WeChatController.cs
@@ -1,11 +1,8 @@
-using System.IO;
-using System.Threading.Tasks;
-using Blog.Core.IServices;
+using Blog.Core.IServices;
using Blog.Core.Model;
using Blog.Core.Model.ViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
-using Microsoft.Extensions.Logging;
namespace Blog.Core.Controllers
{
diff --git a/Blog.Core.Api/Controllers/WeChatPushLogController.cs b/Blog.Core.Api/Controllers/WeChatPushLogController.cs
index 1fe1603d..af168091 100644
--- a/Blog.Core.Api/Controllers/WeChatPushLogController.cs
+++ b/Blog.Core.Api/Controllers/WeChatPushLogController.cs
@@ -1,4 +1,3 @@
-using System.Threading.Tasks;
using Blog.Core.IServices;
using Blog.Core.Model;
using Blog.Core.Model.Models;
diff --git a/Blog.Core.Api/Controllers/WeChatSubController.cs b/Blog.Core.Api/Controllers/WeChatSubController.cs
index bd8d1759..94f982d2 100644
--- a/Blog.Core.Api/Controllers/WeChatSubController.cs
+++ b/Blog.Core.Api/Controllers/WeChatSubController.cs
@@ -1,4 +1,3 @@
-using System.Threading.Tasks;
using Blog.Core.IServices;
using Blog.Core.Model;
using Blog.Core.Model.Models;
diff --git a/Blog.Core.Services/TasksLogServices.cs b/Blog.Core.Services/TasksLogServices.cs
index eac9a739..49393cd4 100644
--- a/Blog.Core.Services/TasksLogServices.cs
+++ b/Blog.Core.Services/TasksLogServices.cs
@@ -5,12 +5,10 @@
using Blog.Core.Model.Models;
using Blog.Core.Services.BASE;
using Blog.Core.Common.Extensions;
-using System.Drawing.Printing;
using SqlSugar;
using Blog.Core.Model;
using System.Collections.Generic;
using System.Linq;
-using OfficeOpenXml.FormulaParsing.Excel.Functions.DateTime;
namespace Blog.Core.Services
{
@@ -43,9 +41,8 @@ public async Task> GetTaskLogs(int jobId, int page, int intP
.ToPageListAsync(page, intPageSize, totalCount);
return new PageModel(page, totalCount, intPageSize, data);
}
- public async Task GetTaskOverview(int jobId, DateTime? runTime, DateTime? endTime,string type)
+ public async Task GetTaskOverview(int jobId, DateTime? runTime, DateTime? endTime, string type)
{
-
//按年
if ("year".Equals(type))
{
@@ -54,7 +51,7 @@ public async Task GetTaskOverview(int jobId, DateTime? runTime, DateTime
var dayArray = new List();
while (days >= 0)
{
- dayArray.Add(new DateTime(runTime.Value.Year + days,1,1));
+ dayArray.Add(new DateTime(runTime.Value.Year + days, 1, 1));
days--;
}
var queryableLeft = this.Db.Reportable(dayArray).ToQueryable();
@@ -66,10 +63,11 @@ public async Task GetTaskOverview(int jobId, DateTime? runTime, DateTime
.Select((x1, x2) => new
{
执行次数 = SqlFunc.AggregateSum(SqlFunc.IIF(x2.Id > 0, 1, 0)),
- date = x1.ColumnName.Year.ToString()+"年"
+ date = x1.ColumnName.Year.ToString() + "年"
}).ToList().OrderBy(t => t.date);
return list;
- }else if ("month".Equals(type))
+ }
+ else if ("month".Equals(type))
{
//按月
var queryableLeft = this.Db.Reportable(ReportableDateType.MonthsInLast1years).ToQueryable(); //生成月份 //ReportableDateType.MonthsInLast1yea 表式近一年月份 并且queryable之后还能在where过滤
@@ -78,7 +76,7 @@ public async Task GetTaskOverview(int jobId, DateTime? runTime, DateTime
//月份和表JOIN
var list = queryableLeft
.LeftJoin(queryableRight, (x1, x2) => x2.RunTime.ToString("MM月") == x1.ColumnName.ToString("MM月"))
-
+
.GroupBy((x1, x2) => x1.ColumnName)
.Select((x1, x2) => new
{
@@ -87,8 +85,10 @@ public async Task GetTaskOverview(int jobId, DateTime? runTime, DateTime
date = x1.ColumnName.ToString("MM月")
}
).ToList().OrderBy(t => t.date);
+ await Task.CompletedTask;
return list;
- }else if ("day".Equals(type))
+ }
+ else if ("day".Equals(type))
{
//按日
var time = runTime.Value;
@@ -97,7 +97,7 @@ public async Task GetTaskOverview(int jobId, DateTime? runTime, DateTime
var queryableLeft = this.Db.Reportable(dayArray).ToQueryable();
var star = Convert.ToDateTime(runTime.Value.ToString("yyyy-MM-01 00:00:00"));
var end = Convert.ToDateTime(runTime.Value.ToString($"yyyy-MM-{days} 23:59:59"));
- var queryableRight = this.Db.Queryable().Where((x) => x.RunTime >= star && x.RunTime <= end); ;; //声名表
+ var queryableRight = this.Db.Queryable().Where((x) => x.RunTime >= star && x.RunTime <= end); ; ; //声名表
var list = this.Db.Queryable(queryableLeft, queryableRight, JoinType.Left,
(x1, x2) => x1.ColumnName.Date == x2.RunTime.Date)
@@ -107,26 +107,30 @@ public async Task GetTaskOverview(int jobId, DateTime? runTime, DateTime
执行次数 = SqlFunc.AggregateSum(SqlFunc.IIF(x2.Id > 0, 1, 0)),
date = x1.ColumnName.Day
}).ToList().OrderBy(t => t.date);
+ await Task.CompletedTask;
return list;
- }else if ("hour".Equals(type))
+ }
+ else if ("hour".Equals(type))
{
//按小时
var time = runTime.Value;
var days = 24;
var dayArray = Enumerable.Range(0, days).Select(it => Convert.ToDateTime(time.ToString($"yyyy-MM-dd {it.ToString().PadLeft(2, '0')}:00:00"))).ToList();//转成时间数组
var queryableLeft = this.Db.Reportable(dayArray).ToQueryable();
- var queryableRight = this.Db.Queryable().Where((x) => x.RunTime >= runTime.Value.Date && x.RunTime<= runTime.Value.Date.AddDays(1).AddMilliseconds(-1)); //声名表
+ var queryableRight = this.Db.Queryable().Where((x) => x.RunTime >= runTime.Value.Date && x.RunTime <= runTime.Value.Date.AddDays(1).AddMilliseconds(-1)); //声名表
var list = this.Db.Queryable(queryableLeft, queryableRight, JoinType.Left,
- (x1, x2) => x1.ColumnName.Hour == x2.RunTime.Hour)
+ (x1, x2) => x1.ColumnName.Hour == x2.RunTime.Hour)
.GroupBy((x1, x2) => x1.ColumnName)
.Select((x1, x2) => new
{
执行次数 = SqlFunc.AggregateSum(SqlFunc.IIF(x2.Id > 0, 1, 0)),
date = x1.ColumnName.Hour
}).ToList().OrderBy(t => t.date);
+ await Task.CompletedTask;
return list;
}
+ await Task.CompletedTask;
return null;
}
}
From d1288b103ecf582d5491712f63e5dbd8c05048dc Mon Sep 17 00:00:00 2001
From: ansonzhang <3143422472@qq.com>
Date: Thu, 23 Mar 2023 16:39:57 +0800
Subject: [PATCH 04/84] Update README.md
---
README.md | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/README.md b/README.md
index 29d427ec..ee36dc2c 100644
--- a/README.md
+++ b/README.md
@@ -73,7 +73,8 @@ Blog.Core 开箱即用的企业级前后端分离【 .NET Core6.0 Api + Vue 2.x
#### 框架模块:
- [x] 采用`仓储+服务+接口`的形式封装框架;
-- [x] 异步 async/await 开发;
+- [x] 自定义项目模板 `CreateYourProject.bat` ,可以一键生成自己的项目;🎶
+- [x] 异步 async/await 开发;
- [x] 接入国产数据库ORM组件 —— SqlSugar,封装数据库操作,支持级联操作;
- [x] 支持自由切换多种数据库,MySql/SqlServer/Sqlite/Oracle/Postgresql/达梦/人大金仓;
- [x] 实现项目启动,自动生成种子数据 ✨;
From 798a7f64228960d181fb296aace484a915a2b919 Mon Sep 17 00:00:00 2001
From: hudingwen <765472804@qq.com>
Date: Fri, 24 Mar 2023 21:24:24 +0800
Subject: [PATCH 05/84] =?UTF-8?q?=E8=AE=A2=E9=98=85=E9=93=BE=E6=8E=A5?=
=?UTF-8?q?=E5=AE=8C=E5=96=84?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
Blog.Core.Api/Controllers/TrojanController.cs | 8 ++++++--
1 file changed, 6 insertions(+), 2 deletions(-)
diff --git a/Blog.Core.Api/Controllers/TrojanController.cs b/Blog.Core.Api/Controllers/TrojanController.cs
index 8ec64c8a..cdb010e8 100644
--- a/Blog.Core.Api/Controllers/TrojanController.cs
+++ b/Blog.Core.Api/Controllers/TrojanController.cs
@@ -15,6 +15,7 @@
using Blog.Core.Model.ViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
+using OfficeOpenXml.FormulaParsing.Excel.Functions.Math;
namespace Blog.Core.Controllers
{
@@ -357,9 +358,12 @@ public async Task>> AddUrlServers(TrojanUrlS
private string GetSplice(TrojanServers item,string passwordshow)
{
if ("0".Equals(item.servertype))
- return $"trojan://{passwordshow}@{item.serveraddress}:{item.serverport}?allowinsecure=0&tfo=0&peer={(string.IsNullOrEmpty(item.serverpeer) ? item.serverpeer : item.serveraddress)}#{item.servername}";
+ return $"trojan://{passwordshow}@{item.serveraddress}:{item.serverport}?allowinsecure=0&tfo=0&fp=chrome&peer={(string.IsNullOrEmpty(item.serverpeer) ? item.serverpeer : item.serveraddress)}#{item.servername}";
else if ("1".Equals(item.servertype))
- return $"trojan://{passwordshow}@{item.serveraddress}:{item.serverport}?wspath={item.serverpath}&ws=1&peer={(string.IsNullOrEmpty(item.serverpeer) ? item.serverpeer : item.serveraddress)}#{item.servername}";
+ {
+ var sni = string.IsNullOrEmpty(item.serverpeer) ? item.serverpeer : item.serveraddress;
+ return $"trojan://{passwordshow}@{item.serveraddress}:{item.serverport}?wspath={item.serverpath}&ws=1&peer={sni}&path={item.serverpath}&host={sni}&fp=chrome&type=ws&sni={sni}#{item.servername}";
+ }
else
return $"servertype:({item.servertype})错误";
}
From 042c4a6c4497437ac09f93d4c9ec8bbb178a92c1 Mon Sep 17 00:00:00 2001
From: hudingwen <765472804@qq.com>
Date: Sun, 26 Mar 2023 15:36:45 +0800
Subject: [PATCH 06/84] fix bug
---
Blog.Core.Api/Controllers/TrojanController.cs | 5 +++--
1 file changed, 3 insertions(+), 2 deletions(-)
diff --git a/Blog.Core.Api/Controllers/TrojanController.cs b/Blog.Core.Api/Controllers/TrojanController.cs
index cdb010e8..d8d005dc 100644
--- a/Blog.Core.Api/Controllers/TrojanController.cs
+++ b/Blog.Core.Api/Controllers/TrojanController.cs
@@ -357,11 +357,12 @@ public async Task>> AddUrlServers(TrojanUrlS
}
private string GetSplice(TrojanServers item,string passwordshow)
{
+ var sni = string.IsNullOrEmpty(item.serverpeer) ? item.serveraddress : item.serverpeer;
if ("0".Equals(item.servertype))
- return $"trojan://{passwordshow}@{item.serveraddress}:{item.serverport}?allowinsecure=0&tfo=0&fp=chrome&peer={(string.IsNullOrEmpty(item.serverpeer) ? item.serverpeer : item.serveraddress)}#{item.servername}";
+ return $"trojan://{passwordshow}@{item.serveraddress}:{item.serverport}?allowinsecure=0&tfo=0&fp=chrome&peer={sni}&host={sni}&sni={sni}#{item.servername}";
else if ("1".Equals(item.servertype))
{
- var sni = string.IsNullOrEmpty(item.serverpeer) ? item.serverpeer : item.serveraddress;
+
return $"trojan://{passwordshow}@{item.serveraddress}:{item.serverport}?wspath={item.serverpath}&ws=1&peer={sni}&path={item.serverpath}&host={sni}&fp=chrome&type=ws&sni={sni}#{item.servername}";
}
else
From 67efee3ee1bd7d8337ee3e4af2667c1139e93b11 Mon Sep 17 00:00:00 2001
From: Nine
Date: Thu, 30 Mar 2023 15:38:17 +0800
Subject: [PATCH 07/84] =?UTF-8?q?Sqlsugar=20=E5=88=86=E8=A1=A8=20CRUD=20de?=
=?UTF-8?q?mo?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
Blog.Core.Api/Blog.Core.xml | 44 ++++
.../Controllers/SplitDemoController.cs | 199 ++++++++++++++++++
Blog.Core.Api/Program.cs | 4 +
Blog.Core.Api/Startup.cs | 4 +
Blog.Core.Common/Helper/NumberConverter.cs | 174 +++++++++++++++
Blog.Core.Common/Seed/DBSeed.cs | 2 +-
Blog.Core.IServices/BASE/IBaseServices.cs | 10 +-
Blog.Core.IServices/ISplitDemoServices.cs | 15 ++
Blog.Core.Model/Models/SplitDemo.cs | 27 +++
Blog.Core.Repository/BASE/BaseRepository.cs | 72 ++++++-
Blog.Core.Repository/BASE/IBaseRepository.cs | 40 ++++
Blog.Core.Services/BASE/BaseServices.cs | 31 +++
Blog.Core.Services/SplitDemoServices.cs | 23 ++
13 files changed, 642 insertions(+), 3 deletions(-)
create mode 100644 Blog.Core.Api/Controllers/SplitDemoController.cs
create mode 100644 Blog.Core.Common/Helper/NumberConverter.cs
create mode 100644 Blog.Core.IServices/ISplitDemoServices.cs
create mode 100644 Blog.Core.Model/Models/SplitDemo.cs
create mode 100644 Blog.Core.Services/SplitDemoServices.cs
diff --git a/Blog.Core.Api/Blog.Core.xml b/Blog.Core.Api/Blog.Core.xml
index 89cb3213..9891d5d9 100644
--- a/Blog.Core.Api/Blog.Core.xml
+++ b/Blog.Core.Api/Blog.Core.xml
@@ -1249,6 +1249,50 @@
+
+
+ 分表demo
+
+
+
+
+ 分页获取数据
+
+
+
+
+
+
+
+
+
+
+ 根据ID获取信息
+
+
+
+
+
+
+ 添加一条测试数据
+
+
+
+
+
+
+ 修改一条测试数据
+
+
+
+
+
+
+ 根据id删除数据
+
+
+
+
多租户-多库方案 测试
diff --git a/Blog.Core.Api/Controllers/SplitDemoController.cs b/Blog.Core.Api/Controllers/SplitDemoController.cs
new file mode 100644
index 00000000..fb3c03c6
--- /dev/null
+++ b/Blog.Core.Api/Controllers/SplitDemoController.cs
@@ -0,0 +1,199 @@
+using Blog.Core.IServices;
+using Blog.Core.Model;
+using Blog.Core.Model.Models;
+using Blog.Core.Repository.UnitOfWorks;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Mvc;
+using System.Linq.Expressions;
+
+namespace Blog.Core.Api.Controllers
+{
+ ///
+ /// 分表demo
+ ///
+ [Route("api/[controller]/[action]")]
+ [ApiController]
+ [Authorize(Permissions.Name)]
+ public class SplitDemoController : ControllerBase
+ {
+ readonly ISplitDemoServices splitDemoServices;
+ readonly IUnitOfWorkManage unitOfWorkManage;
+ public SplitDemoController(ISplitDemoServices _splitDemoServices, IUnitOfWorkManage _unitOfWorkManage)
+ {
+ splitDemoServices = _splitDemoServices;
+ unitOfWorkManage = _unitOfWorkManage;
+ }
+
+ ///
+ /// 分页获取数据
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ [HttpGet]
+ [AllowAnonymous]
+ public async Task>> Get(DateTime beginTime, DateTime endTime, int page = 1, string key = "", int pageSize = 10)
+ {
+ if (string.IsNullOrEmpty(key) || string.IsNullOrWhiteSpace(key))
+ {
+ key = "";
+ }
+ Expression> whereExpression = a => (a.Name != null && a.Name.Contains(key));
+ var data = await splitDemoServices.QueryPageSplit(whereExpression, beginTime, endTime, page, pageSize, " Id desc ");
+ return MessageModel>.Message(data.dataCount >= 0, "获取成功", data);
+ }
+
+ ///
+ /// 根据ID获取信息
+ ///
+ ///
+ ///
+ [HttpGet]
+ [AllowAnonymous]
+ public async Task> GetById(long id)
+ {
+ var data = new MessageModel();
+ var model = await splitDemoServices.QueryByIdSplit(id);
+ if (model != null)
+ {
+ return MessageModel.Success("获取成功", model);
+ }
+ else
+ {
+ return MessageModel.Fail("获取失败");
+ }
+ }
+
+ ///
+ /// 添加一条测试数据
+ ///
+ ///
+ ///
+ [HttpPost]
+ [AllowAnonymous]
+ public async Task> Post([FromBody] SplitDemo splitDemo)
+ {
+ var data = new MessageModel();
+ unitOfWorkManage.BeginTran();
+ var id = (await splitDemoServices.AddSplit(splitDemo));
+ data.success = (id == null ? false : true);
+ try
+ {
+ if (data.success)
+ {
+ data.response = id.FirstOrDefault().ToString();
+ data.msg = "添加成功";
+ }
+ else
+ {
+ data.msg = "添加失败";
+ }
+ }
+ catch (Exception)
+ {
+ throw;
+ }
+ finally
+ {
+ if (data.success)
+ unitOfWorkManage.CommitTran();
+ else
+ unitOfWorkManage.RollbackTran();
+ }
+ return data;
+ }
+
+ ///
+ /// 修改一条测试数据
+ ///
+ ///
+ ///
+ [HttpPut]
+ [AllowAnonymous]
+ public async Task> Put([FromBody] SplitDemo splitDemo)
+ {
+ var data = new MessageModel();
+ if (splitDemo != null && splitDemo.Id > 0)
+ {
+ unitOfWorkManage.BeginTran();
+ data.success = await splitDemoServices.UpdateSplit(splitDemo, splitDemo.CreateTime);
+ try
+ {
+ if (data.success)
+ {
+ data.msg = "修改成功";
+ data.response = splitDemo?.Id.ObjToString();
+ }
+ else
+ {
+ data.msg = "修改失败";
+ }
+ }
+ catch (Exception)
+ {
+ throw;
+ }
+ finally
+ {
+ if (data.success)
+ unitOfWorkManage.CommitTran();
+ else
+ unitOfWorkManage.RollbackTran();
+ }
+ }
+ return data;
+ }
+
+ ///
+ /// 根据id删除数据
+ ///
+ ///
+ ///
+ [HttpDelete]
+ [AllowAnonymous]
+ public async Task> Delete(long id)
+ {
+ var data = new MessageModel();
+
+ var model = await splitDemoServices.QueryByIdSplit(id);
+ if (model != null)
+ {
+ unitOfWorkManage.BeginTran();
+ data.success = await splitDemoServices.DeleteSplit(model,model.CreateTime);
+ try
+ {
+ data.response = id.ObjToString();
+ if (data.success)
+ {
+ data.msg = "删除成功";
+ }
+ else
+ {
+ data.msg = "删除失败";
+ }
+
+ }
+ catch (Exception)
+ {
+ throw;
+ }
+ finally
+ {
+ if (data.success)
+ unitOfWorkManage.CommitTran();
+ else
+ unitOfWorkManage.RollbackTran();
+ }
+ }
+ else
+ {
+ data.msg = "不存在";
+ }
+ return data;
+
+ }
+ }
+}
diff --git a/Blog.Core.Api/Program.cs b/Blog.Core.Api/Program.cs
index f5223beb..2a75498e 100644
--- a/Blog.Core.Api/Program.cs
+++ b/Blog.Core.Api/Program.cs
@@ -7,6 +7,7 @@
using Blog.Core;
using Blog.Core.Common;
using Blog.Core.Common.Core;
+using Blog.Core.Common.Helper;
using Blog.Core.Common.LogHelper;
using Blog.Core.Extensions;
using Blog.Core.Extensions.Apollo;
@@ -14,6 +15,7 @@
using Blog.Core.Filter;
using Blog.Core.Hubs;
using Blog.Core.IServices;
+using Blog.Core.Model;
using Blog.Core.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
@@ -111,6 +113,8 @@
//options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local;
options.SerializerSettings.Converters.Add(new StringEnumConverter());
+ //将long类型转为string
+ options.SerializerSettings.Converters.Add(new NumberConverter(NumberConverterShip.Int64));
})
//.AddFluentValidation(config =>
//{
diff --git a/Blog.Core.Api/Startup.cs b/Blog.Core.Api/Startup.cs
index bc1630f1..4f99b621 100644
--- a/Blog.Core.Api/Startup.cs
+++ b/Blog.Core.Api/Startup.cs
@@ -3,6 +3,7 @@
using System.Text;
using Autofac;
using Blog.Core.Common;
+using Blog.Core.Common.Helper;
using Blog.Core.Common.LogHelper;
using Blog.Core.Common.Seed;
using Blog.Core.Extensions;
@@ -10,6 +11,7 @@
using Blog.Core.Filter;
using Blog.Core.Hubs;
using Blog.Core.IServices;
+using Blog.Core.Model;
using Blog.Core.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
@@ -123,6 +125,8 @@ public void ConfigureServices(IServiceCollection services)
options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local;
//添加Enum转string
options.SerializerSettings.Converters.Add(new StringEnumConverter());
+ //将long类型转为string
+ options.SerializerSettings.Converters.Add(new NumberConverter(NumberConverterShip.Int64));
});
services.Replace(ServiceDescriptor.Transient());
diff --git a/Blog.Core.Common/Helper/NumberConverter.cs b/Blog.Core.Common/Helper/NumberConverter.cs
new file mode 100644
index 00000000..27890faf
--- /dev/null
+++ b/Blog.Core.Common/Helper/NumberConverter.cs
@@ -0,0 +1,174 @@
+using Newtonsoft.Json;
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Blog.Core.Common.Helper
+{
+ ///
+ ///
+ /// 大数据json序列化重写
+ ///
+ public sealed class NumberConverter : JsonConverter
+ {
+ ///
+ /// 转换成字符串的类型
+ ///
+ private readonly NumberConverterShip _ship;
+
+ ///
+ /// 大数据json序列化重写实例化
+ ///
+ public NumberConverter()
+ {
+ _ship = (NumberConverterShip)0xFF;
+ }
+
+ ///
+ /// 大数据json序列化重写实例化
+ ///
+ /// 转换成字符串的类型
+ public NumberConverter(NumberConverterShip ship)
+ {
+ _ship = ship;
+ }
+
+ ///
+ ///
+ /// 确定此实例是否可以转换指定的对象类型。
+ ///
+ /// 对象的类型。
+ /// 如果此实例可以转换指定的对象类型,则为:true,否则为:false
+ public override bool CanConvert(Type objectType)
+ {
+ var typecode = Type.GetTypeCode(objectType.Name.Equals("Nullable`1") ? objectType.GetGenericArguments().First() : objectType);
+ switch (typecode)
+ {
+ case TypeCode.Decimal:
+ return (_ship & NumberConverterShip.Decimal) == NumberConverterShip.Decimal;
+ case TypeCode.Double:
+ return (_ship & NumberConverterShip.Double) == NumberConverterShip.Double;
+ case TypeCode.Int64:
+ return (_ship & NumberConverterShip.Int64) == NumberConverterShip.Int64;
+ case TypeCode.UInt64:
+ return (_ship & NumberConverterShip.UInt64) == NumberConverterShip.UInt64;
+ case TypeCode.Single:
+ return (_ship & NumberConverterShip.Single) == NumberConverterShip.Single;
+ default: return false;
+ }
+ }
+
+ ///
+ ///
+ /// 读取对象的JSON表示。
+ ///
+ /// 从 中读取。
+ /// 对象的类型。
+ /// 正在读取的对象的现有值。
+ /// 调用的序列化器实例。
+ /// 对象值。
+ public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
+ {
+ return AsType(reader.Value.ToString(), objectType);
+ }
+
+ ///
+ /// 字符串格式数据转其他类型数据
+ ///
+ /// 输入的字符串
+ /// 目标格式
+ /// 转换结果
+ public static object AsType(string input, Type destinationType)
+ {
+ try
+ {
+ var converter = TypeDescriptor.GetConverter(destinationType);
+ if (converter.CanConvertFrom(typeof(string)))
+ {
+ return converter.ConvertFrom(null, null, input);
+ }
+
+ converter = TypeDescriptor.GetConverter(typeof(string));
+ if (converter.CanConvertTo(destinationType))
+ {
+ return converter.ConvertTo(null, null, input, destinationType);
+ }
+ }
+ catch
+ {
+ return null;
+ }
+ return null;
+ }
+
+ ///
+ ///
+ /// 写入对象的JSON表示形式。
+ ///
+ /// 要写入的 。
+ /// 要写入对象值
+ /// 调用的序列化器实例。
+ public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
+ {
+ if (value == null)
+ {
+ writer.WriteNull();
+ }
+ else
+ {
+ var objectType = value.GetType();
+ var typeCode = Type.GetTypeCode(objectType.Name.Equals("Nullable`1") ? objectType.GetGenericArguments().First() : objectType);
+ switch (typeCode)
+ {
+ case TypeCode.Decimal:
+ writer.WriteValue(((decimal)value).ToString("f6"));
+ break;
+ case TypeCode.Double:
+ writer.WriteValue(((double)value).ToString("f4"));
+ break;
+ case TypeCode.Single:
+ writer.WriteValue(((float)value).ToString("f2"));
+ break;
+ default:
+ writer.WriteValue(value.ToString());
+ break;
+ }
+ }
+ }
+ }
+
+ ///
+ /// 转换成字符串的类型
+ ///
+ [Flags]
+ public enum NumberConverterShip
+ {
+ ///
+ /// 长整数
+ ///
+ Int64 = 1,
+
+ ///
+ /// 无符号长整数
+ ///
+ UInt64 = 2,
+
+ ///
+ /// 浮点数
+ ///
+ Single = 4,
+
+ ///
+ /// 双精度浮点数
+ ///
+ Double = 8,
+
+ ///
+ /// 大数字
+ ///
+ Decimal =16
+ }
+}
diff --git a/Blog.Core.Common/Seed/DBSeed.cs b/Blog.Core.Common/Seed/DBSeed.cs
index 7b594109..fb13768a 100644
--- a/Blog.Core.Common/Seed/DBSeed.cs
+++ b/Blog.Core.Common/Seed/DBSeed.cs
@@ -109,7 +109,7 @@ public static async Task SeedAsync(MyContext myContext, string WebRootPath)
if (!myContext.Db.DbMaintenance.IsAnyTable(t.Name))
{
Console.WriteLine(t.Name);
- myContext.Db.CodeFirst.InitTables(t);
+ myContext.Db.CodeFirst.SplitTables().InitTables(t);
}
});
ConsoleHelper.WriteSuccessLine($"Tables created successfully!");
diff --git a/Blog.Core.IServices/BASE/IBaseServices.cs b/Blog.Core.IServices/BASE/IBaseServices.cs
index 7856f8bf..4091b978 100644
--- a/Blog.Core.IServices/BASE/IBaseServices.cs
+++ b/Blog.Core.IServices/BASE/IBaseServices.cs
@@ -23,7 +23,7 @@ public interface IBaseServices where TEntity : class
Task DeleteById(object id);
Task Delete(TEntity model);
-
+
Task DeleteByIds(object[] ids);
Task Update(TEntity model);
@@ -59,6 +59,14 @@ Task> QueryMuch(
Expression> selectExpression,
Expression> whereLambda = null) where T : class, new();
Task> QueryPage(PaginationModel pagination);
+
+ #region 分表
+ Task QueryByIdSplit(object objId);
+ Task> AddSplit(TEntity entity);
+ Task DeleteSplit(TEntity entity, DateTime dateTime);
+ Task UpdateSplit(TEntity entity, DateTime dateTime);
+ Task> QueryPageSplit(Expression> whereExpression, DateTime beginTime, DateTime endTime, int pageIndex = 1, int pageSize = 20, string orderByFields = null);
+ #endregion
}
}
diff --git a/Blog.Core.IServices/ISplitDemoServices.cs b/Blog.Core.IServices/ISplitDemoServices.cs
new file mode 100644
index 00000000..55215761
--- /dev/null
+++ b/Blog.Core.IServices/ISplitDemoServices.cs
@@ -0,0 +1,15 @@
+
+
+using Blog.Core.IServices.BASE;
+using Blog.Core.Model.Models;
+using System.Threading.Tasks;
+
+namespace Blog.Core.IServices
+{
+ ///
+ /// sysUserInfoServices
+ ///
+ public interface ISplitDemoServices : IBaseServices
+ {
+ }
+}
diff --git a/Blog.Core.Model/Models/SplitDemo.cs b/Blog.Core.Model/Models/SplitDemo.cs
new file mode 100644
index 00000000..26329935
--- /dev/null
+++ b/Blog.Core.Model/Models/SplitDemo.cs
@@ -0,0 +1,27 @@
+using Newtonsoft.Json;
+using SqlSugar;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Text.Json.Serialization;
+using System.Threading.Tasks;
+
+namespace Blog.Core.Model.Models
+{
+ [SplitTable(SplitType.Day)]//按年分表 (自带分表支持 年、季、月、周、日)
+ [SugarTable("SplitDemo_{year}{month}{day}")]//3个变量必须要有,这么设计为了兼容开始按年,后面改成按月、按日
+ public class SplitDemo
+ {
+ [SugarColumn(IsPrimaryKey = true)]
+ public long Id { get; set; }
+
+ public string Name { get; set; }
+
+ [SugarColumn(IsNullable = true)]//设置为可空字段 (更多用法看文档 迁移)
+ public DateTime UpdateTime { get; set; }
+
+ [SplitField] //分表字段 在插入的时候会根据这个字段插入哪个表,在更新删除的时候用这个字段找出相关表
+ public DateTime CreateTime { get; set; }
+ }
+}
diff --git a/Blog.Core.Repository/BASE/BaseRepository.cs b/Blog.Core.Repository/BASE/BaseRepository.cs
index 828f9506..3048baa8 100644
--- a/Blog.Core.Repository/BASE/BaseRepository.cs
+++ b/Blog.Core.Repository/BASE/BaseRepository.cs
@@ -5,6 +5,7 @@
using Blog.Core.Model.Models;
using Blog.Core.Model.Tenants;
using Blog.Core.Repository.UnitOfWorks;
+using OfficeOpenXml.FormulaParsing.Excel.Functions.DateTime;
using SqlSugar;
using System;
using System.Collections.Generic;
@@ -127,7 +128,6 @@ public async Task Add(TEntity entity)
return await insert.ExecuteReturnIdentityAsync();
}
-
///
/// 写入实体数据
///
@@ -557,5 +557,75 @@ public async Task> QueryTabsPage(
// groupName = s.groupName,
// jobName = s.jobName
// }, exp, s => new { s.uID, s.uRealName, s.groupName, s.jobName }, model.currentPage, model.pageSize, model.orderField + " " + model.orderType);
+ #region Split分表基础接口 (基础CRUD)
+ ///
+ /// 分页查询[使用版本,其他分页未测试]
+ ///
+ /// 条件表达式
+ /// 页码(下标0)
+ /// 页大小
+ /// 排序字段,如name asc,age desc
+ ///
+ public async Task> QueryPageSplit(Expression> whereExpression, DateTime beginTime, DateTime endTime, int pageIndex = 1, int pageSize = 20, string orderByFields = null)
+ {
+ RefAsync totalCount = 0;
+ var list = await _db.Queryable().SplitTable(beginTime, endTime)
+ .OrderByIF(!string.IsNullOrEmpty(orderByFields), orderByFields)
+ .WhereIF(whereExpression != null, whereExpression)
+ .ToPageListAsync(pageIndex, pageSize, totalCount);
+ var data= new PageModel(pageIndex, totalCount, pageSize, list);
+ return data;
+ }
+ ///
+ /// 写入实体数据
+ ///
+ /// 数据实体
+ ///
+ public async Task> AddSplit(TEntity entity)
+ {
+ var insert = _db.Insertable(entity).SplitTable();
+ //插入并返回雪花ID并且自动赋值ID
+ return await insert.ExecuteReturnSnowflakeIdListAsync();
+ }
+
+ ///
+ /// 更新实体数据
+ ///
+ /// 数据实体
+ ///
+ public async Task UpdateSplit(TEntity entity, DateTime dateTime)
+ {
+ //直接根据实体集合更新 (全自动 找表更新)
+ //return await _db.Updateable(entity).SplitTable().ExecuteCommandAsync();//,SplitTable不能少
+
+ //精准找单个表
+ var tableName = _db.SplitHelper().GetTableName(dateTime);//根据时间获取表名
+ return await _db.Updateable(entity).AS(tableName).ExecuteCommandHasChangeAsync();
+ }
+ ///
+ /// 删除数据
+ ///
+ ///
+ ///
+ ///
+ public async Task DeleteSplit(TEntity entity,DateTime dateTime)
+ {
+ ////直接根据实体集合删除 (全自动 找表插入),返回受影响数
+ //return await _db.Deleteable(entity).SplitTable().ExecuteCommandAsync();//,SplitTable不能少
+
+ //精准找单个表
+ var tableName = _db.SplitHelper().GetTableName(dateTime);//根据时间获取表名
+ return await _db.Deleteable().AS(tableName).Where(entity).ExecuteCommandHasChangeAsync();
+ }
+ ///
+ /// 根据ID查找数据
+ ///
+ ///
+ ///
+ public async Task QueryByIdSplit(object objId)
+ {
+ return await _db.Queryable().In(objId).SplitTable(tabs => tabs).SingleAsync();
+ }
+ #endregion
}
}
\ No newline at end of file
diff --git a/Blog.Core.Repository/BASE/IBaseRepository.cs b/Blog.Core.Repository/BASE/IBaseRepository.cs
index 29783505..5f70a4be 100644
--- a/Blog.Core.Repository/BASE/IBaseRepository.cs
+++ b/Blog.Core.Repository/BASE/IBaseRepository.cs
@@ -208,5 +208,45 @@ Task> QueryTabsPage(
int pageIndex = 1,
int pageSize = 20,
string orderByFields = null);
+
+ #region 分表
+ ///
+ /// 通过ID查询
+ ///
+ ///
+ ///
+ Task QueryByIdSplit(object objId);
+ ///
+ /// 自动分表插入
+ ///
+ ///
+ ///
+ Task> AddSplit(TEntity entity);
+ ///
+ /// 删除
+ ///
+ ///
+ ///
+ ///
+ Task DeleteSplit(TEntity entity, DateTime dateTime);
+ ///
+ /// 更新
+ ///
+ ///
+ ///
+ ///
+ Task UpdateSplit(TEntity entity, DateTime dateTime);
+ ///
+ /// 分页查询
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ Task> QueryPageSplit(Expression> whereExpression, DateTime beginTime, DateTime endTime, int pageIndex = 1, int pageSize = 20, string orderByFields = null);
+ #endregion
}
}
diff --git a/Blog.Core.Services/BASE/BaseServices.cs b/Blog.Core.Services/BASE/BaseServices.cs
index f8105165..7ee55eb1 100644
--- a/Blog.Core.Services/BASE/BaseServices.cs
+++ b/Blog.Core.Services/BASE/BaseServices.cs
@@ -332,5 +332,36 @@ public async Task> QueryPage(PaginationModel pagination)
var express = DynamicLinqFactory.CreateLambda(pagination.Conditions);
return await QueryPage(express, pagination.PageIndex, pagination.PageSize, pagination.OrderByFileds);
}
+ #region 分表
+ public async Task> AddSplit(TEntity entity)
+ {
+ return await BaseDal.AddSplit(entity);
+ }
+ public async Task UpdateSplit(TEntity entity, DateTime dateTime)
+ {
+ return await BaseDal.UpdateSplit(entity, dateTime);
+ }
+
+ ///
+ /// 根据实体删除一条数据
+ ///
+ /// 博文实体类
+ ///
+ public async Task DeleteSplit(TEntity entity, DateTime dateTime)
+ {
+ return await BaseDal.DeleteSplit(entity, dateTime);
+ }
+
+ public async Task QueryByIdSplit(object objId)
+ {
+ return await BaseDal.QueryByIdSplit(objId);
+ }
+ public async Task> QueryPageSplit(Expression> whereExpression, DateTime beginTime, DateTime endTime,
+ int pageIndex = 1, int pageSize = 20, string orderByFields = null)
+ {
+ return await BaseDal.QueryPageSplit(whereExpression, beginTime, endTime,
+ pageIndex, pageSize, orderByFields);
+ }
+ #endregion
}
}
\ No newline at end of file
diff --git a/Blog.Core.Services/SplitDemoServices.cs b/Blog.Core.Services/SplitDemoServices.cs
new file mode 100644
index 00000000..cf8e2cc1
--- /dev/null
+++ b/Blog.Core.Services/SplitDemoServices.cs
@@ -0,0 +1,23 @@
+using Blog.Core.IRepository.Base;
+using Blog.Core.IServices;
+using Blog.Core.Model.Models;
+using Blog.Core.Services.BASE;
+using System.Linq;
+using System.Threading.Tasks;
+
+namespace Blog.Core.FrameWork.Services
+{
+ ///
+ /// sysUserInfoServices
+ ///
+ public class SplitDemoServices : BaseServices, ISplitDemoServices
+ {
+ private readonly IBaseRepository _splitDemoRepository;
+ public SplitDemoServices(IBaseRepository splitDemoRepository)
+ {
+ _splitDemoRepository = splitDemoRepository;
+ }
+
+
+ }
+}
From 7b1f3a4c740f6cc7302219a12bb1033ab583018c Mon Sep 17 00:00:00 2001
From: anjoy8 <3143422472@qq.com>
Date: Thu, 30 Mar 2023 15:49:30 +0800
Subject: [PATCH 08/84] feat: :airplane: change id to long
---
Blog.Core.Api/Blog.Core.Model.xml | 5 ---
Blog.Core.Api/Blog.Core.xml | 4 +-
.../Controllers/DbFirst/MigrateController.cs | 30 ++++++-------
.../Controllers/DepartmentController.cs | 2 +-
.../Controllers/PermissionController.cs | 24 +++++-----
Blog.Core.Api/Controllers/UserController.cs | 6 +--
.../wwwroot/BlogCore.Data.json/Permission.tsv | 44 +++++++++----------
.../RoleModulePermission.tsv | 12 ++---
Blog.Core.Common/DB/Aop/SqlsugarAop.cs | 10 ++++-
Blog.Core.Common/Helper/RecursionHelper.cs | 12 ++---
Blog.Core.Common/Seed/DBSeed.cs | 30 +++++++------
.../IRoleModulePermissionServices.cs | 2 +-
Blog.Core.Model/Models/AccessTrendLog.cs | 2 +-
Blog.Core.Model/Models/Advertisement.cs | 2 +-
Blog.Core.Model/Models/BlogArticle.cs | 4 +-
Blog.Core.Model/Models/BlogArticleComment.cs | 2 +-
Blog.Core.Model/Models/Department.cs | 2 +-
Blog.Core.Model/Models/GblLogAudit.cs | 4 +-
Blog.Core.Model/Models/Guestbook.cs | 6 +--
Blog.Core.Model/Models/Modules.cs | 2 +-
Blog.Core.Model/Models/OperateLog.cs | 2 +-
Blog.Core.Model/Models/PasswordLib.cs | 6 +--
Blog.Core.Model/Models/Permission.cs | 2 +-
Blog.Core.Model/Models/Role.cs | 2 +-
.../Models/RoleModulePermission.cs | 2 +-
Blog.Core.Model/Models/RootEntity.cs | 15 -------
Blog.Core.Model/Models/TasksLog.cs | 4 +-
Blog.Core.Model/Models/TasksQz.cs | 2 +-
Blog.Core.Model/Models/TestModels.cs | 6 +--
Blog.Core.Model/Models/Topic.cs | 2 +-
Blog.Core.Model/Models/TopicDetail.cs | 2 +-
Blog.Core.Model/Models/UserRole.cs | 6 +--
Blog.Core.Model/Models/sysUserInfo.cs | 4 +-
Blog.Core.Model/ViewModels/BlogViewModels.cs | 4 +-
.../IRoleModulePermissionRepository.cs | 2 +-
.../RoleModulePermissionRepository.cs | 2 +-
.../RoleModulePermissionServices.cs | 2 +-
37 files changed, 130 insertions(+), 140 deletions(-)
delete mode 100644 Blog.Core.Model/Models/RootEntity.cs
diff --git a/Blog.Core.Api/Blog.Core.Model.xml b/Blog.Core.Api/Blog.Core.Model.xml
index 6bbfd4fe..fe62d8e2 100644
--- a/Blog.Core.Api/Blog.Core.Model.xml
+++ b/Blog.Core.Api/Blog.Core.Model.xml
@@ -1795,11 +1795,6 @@
修改时间
-
-
- ID
-
-
部门表
diff --git a/Blog.Core.Api/Blog.Core.xml b/Blog.Core.Api/Blog.Core.xml
index 89cb3213..faf9d522 100644
--- a/Blog.Core.Api/Blog.Core.xml
+++ b/Blog.Core.Api/Blog.Core.xml
@@ -413,14 +413,14 @@
-
+
获取路由树
-
+
获取路由树
diff --git a/Blog.Core.Api/Controllers/DbFirst/MigrateController.cs b/Blog.Core.Api/Controllers/DbFirst/MigrateController.cs
index 8006d1fb..7865cc69 100644
--- a/Blog.Core.Api/Controllers/DbFirst/MigrateController.cs
+++ b/Blog.Core.Api/Controllers/DbFirst/MigrateController.cs
@@ -81,7 +81,7 @@ public async Task> DataMigrateFromOld2New()
InitPermissionTree(permissions, permissionsAllList, apiList);
var actionPermissionIds = permissionsAllList.Where(d => d.Id >= filterPermissionId).Select(d => d.Id).ToList();
- List filterPermissionIds = new();
+ List filterPermissionIds = new();
FilterPermissionTree(permissionsAllList, actionPermissionIds, filterPermissionIds);
permissions = permissions.Where(d => filterPermissionIds.Contains(d.Id)).ToList();
@@ -93,10 +93,10 @@ public async Task> DataMigrateFromOld2New()
// 1、保持菜单和接口
await SavePermissionTreeAsync(permissions, pms);
- var rid = 0;
- var pid = 0;
- var mid = 0;
- var rpmid = 0;
+ long rid = 0;
+ long pid = 0;
+ long mid = 0;
+ long rpmid = 0;
// 2、保存关系表
foreach (var item in rmps)
@@ -116,8 +116,8 @@ public async Task> DataMigrateFromOld2New()
}
}
- pid = (pms.FirstOrDefault(d => d.PidOld == item.PermissionId)?.PidNew).ObjToInt();
- mid = (pms.FirstOrDefault(d => d.MidOld == item.ModuleId)?.MidNew).ObjToInt();
+ pid = (pms.FirstOrDefault(d => d.PidOld == item.PermissionId)?.PidNew).ObjToLong();
+ mid = (pms.FirstOrDefault(d => d.MidOld == item.ModuleId)?.MidNew).ObjToLong();
// 关系
if (rid > 0 && pid > 0)
{
@@ -282,7 +282,7 @@ private void InitPermissionTree(List permissionsTree, List permissionsAll, List actionPermissionId, List filterPermissionIds)
+ private void FilterPermissionTree(List permissionsAll, List actionPermissionId, List filterPermissionIds)
{
actionPermissionId = actionPermissionId.Distinct().ToList();
var doneIds = permissionsAll.Where(d => actionPermissionId.Contains(d.Id) && d.Pid == 0).Select(d => d.Id).ToList();
@@ -295,7 +295,7 @@ private void FilterPermissionTree(List permissionsAll, List act
}
}
- private async Task SavePermissionTreeAsync(List permissionsTree, List pms, int permissionId = 0)
+ private async Task SavePermissionTreeAsync(List permissionsTree, List pms, long permissionId = 0)
{
var parendId = permissionId;
@@ -304,9 +304,9 @@ private async Task SavePermissionTreeAsync(List permissionsTree, Lis
PM pm = new PM();
// 保留原始主键id
pm.PidOld = item.Id;
- pm.MidOld = (item.Module?.Id).ObjToInt();
+ pm.MidOld = (item.Module?.Id).ObjToLong();
- var mid = 0;
+ long mid = 0;
// 接口
if (item.Module != null)
{
@@ -351,9 +351,9 @@ private async Task SavePermissionTreeAsync(List permissionsTree, Lis
public class PM
{
- public int PidOld { get; set; }
- public int MidOld { get; set; }
- public int PidNew { get; set; }
- public int MidNew { get; set; }
+ public long PidOld { get; set; }
+ public long MidOld { get; set; }
+ public long PidNew { get; set; }
+ public long MidNew { get; set; }
}
}
diff --git a/Blog.Core.Api/Controllers/DepartmentController.cs b/Blog.Core.Api/Controllers/DepartmentController.cs
index bca7bf6d..b8174e90 100644
--- a/Blog.Core.Api/Controllers/DepartmentController.cs
+++ b/Blog.Core.Api/Controllers/DepartmentController.cs
@@ -83,7 +83,7 @@ public async Task>> GetTreeTable(long f = 0, strin
foreach (var item in departments)
{
- List pidarr = new() { };
+ List pidarr = new() { };
var parent = departmentList.FirstOrDefault(d => d.Id == item.Pid);
while (parent != null)
diff --git a/Blog.Core.Api/Controllers/PermissionController.cs b/Blog.Core.Api/Controllers/PermissionController.cs
index 70f8f689..9277a36b 100644
--- a/Blog.Core.Api/Controllers/PermissionController.cs
+++ b/Blog.Core.Api/Controllers/PermissionController.cs
@@ -99,7 +99,7 @@ public async Task>> Get(int page = 1, string
var permissionAll = await _permissionServices.Query(d => d.IsDeleted != true);
foreach (var item in permissionsView)
{
- List pidarr = new List
+ List pidarr = new()
{
item.Pid
};
@@ -177,7 +177,7 @@ public async Task>> GetTreeTable(int f = 0, string
foreach (var item in permissions)
{
- List pidarr = new List { };
+ List pidarr = new() { };
var parent = permissionsList.FirstOrDefault(d => d.Id == item.Pid);
while (parent != null)
@@ -353,13 +353,13 @@ orderby child.Id
///
///
[HttpGet]
- public async Task> GetNavigationBar(int uid)
+ public async Task> GetNavigationBar(long uid)
{
var data = new MessageModel();
var uidInHttpcontext1 = 0;
- var roleIds = new List();
+ var roleIds = new List();
// ids4和jwt切换
if (Permissions.IsUseIds4)
{
@@ -369,13 +369,13 @@ public async Task> GetNavigationBar(int uid)
select item.Value).FirstOrDefault().ObjToInt();
roleIds = (from item in _httpContext.HttpContext.User.Claims
where item.Type == "role"
- select item.Value.ObjToInt()).ToList();
+ select item.Value.ObjToLong()).ToList();
}
else
{
// jwt
uidInHttpcontext1 = ((JwtHelper.SerializeJwt(_httpContext.HttpContext.Request.Headers["Authorization"].ObjToString().Replace("Bearer ", "")))?.Uid).ObjToInt();
- roleIds = (await _userRoleServices.Query(d => d.IsDeleted == false && d.UserId == uid)).Select(d => d.RoleId.ObjToInt()).Distinct().ToList();
+ roleIds = (await _userRoleServices.Query(d => d.IsDeleted == false && d.UserId == uid)).Select(d => d.RoleId.ObjToLong()).Distinct().ToList();
}
@@ -383,7 +383,7 @@ public async Task> GetNavigationBar(int uid)
{
if (roleIds.Any())
{
- var pids = (await _roleModulePermissionServices.Query(d => d.IsDeleted == false && roleIds.Contains(d.RoleId))).Select(d => d.PermissionId.ObjToInt()).Distinct();
+ var pids = (await _roleModulePermissionServices.Query(d => d.IsDeleted == false && roleIds.Contains(d.RoleId))).Select(d => d.PermissionId.ObjToLong()).Distinct();
if (pids.Any())
{
var rolePermissionMoudles = (await _permissionServices.Query(d => pids.Contains(d.Id))).OrderBy(c => c.OrderSort);
@@ -445,12 +445,12 @@ orderby child.Id
///
///
[HttpGet]
- public async Task>> GetNavigationBarPro(int uid)
+ public async Task>> GetNavigationBarPro(long uid)
{
var data = new MessageModel>();
var uidInHttpcontext1 = 0;
- var roleIds = new List();
+ var roleIds = new List();
// ids4和jwt切换
if (Permissions.IsUseIds4)
{
@@ -460,13 +460,13 @@ public async Task>> GetNavigationBarPro(int
select item.Value).FirstOrDefault().ObjToInt();
roleIds = (from item in _httpContext.HttpContext.User.Claims
where item.Type == "role"
- select item.Value.ObjToInt()).ToList();
+ select item.Value.ObjToLong()).ToList();
}
else
{
// jwt
uidInHttpcontext1 = ((JwtHelper.SerializeJwt(_httpContext.HttpContext.Request.Headers["Authorization"].ObjToString().Replace("Bearer ", "")))?.Uid).ObjToInt();
- roleIds = (await _userRoleServices.Query(d => d.IsDeleted == false && d.UserId == uid)).Select(d => d.RoleId.ObjToInt()).Distinct().ToList();
+ roleIds = (await _userRoleServices.Query(d => d.IsDeleted == false && d.UserId == uid)).Select(d => d.RoleId.ObjToLong()).Distinct().ToList();
}
if (uid > 0 && uid == uidInHttpcontext1)
@@ -474,7 +474,7 @@ public async Task>> GetNavigationBarPro(int
if (roleIds.Any())
{
var pids = (await _roleModulePermissionServices.Query(d => d.IsDeleted == false && roleIds.Contains(d.RoleId)))
- .Select(d => d.PermissionId.ObjToInt()).Distinct();
+ .Select(d => d.PermissionId.ObjToLong()).Distinct();
if (pids.Any())
{
var rolePermissionMoudles = (await _permissionServices.Query(d => pids.Contains(d.Id) && d.IsButton == false)).OrderBy(c => c.OrderSort);
diff --git a/Blog.Core.Api/Controllers/UserController.cs b/Blog.Core.Api/Controllers/UserController.cs
index 43f7f610..27989821 100644
--- a/Blog.Core.Api/Controllers/UserController.cs
+++ b/Blog.Core.Api/Controllers/UserController.cs
@@ -103,15 +103,15 @@ public async Task>> Get(int page = 1, str
return Success(data.ConvertTo(_mapper));
}
- private (string, List) GetFullDepartmentName(List departments, int departmentId)
+ private (string, List) GetFullDepartmentName(List departments, int departmentId)
{
var departmentModel = departments.FirstOrDefault(d => d.Id == departmentId);
if (departmentModel == null)
{
- return ("", new List());
+ return ("", new List());
}
- var pids = departmentModel.CodeRelationship?.TrimEnd(',').Split(',').Select(d => d.ObjToInt()).ToList();
+ var pids = departmentModel.CodeRelationship?.TrimEnd(',').Split(',').Select(d => d.ObjToLong()).ToList();
pids.Add(departmentModel.Id);
var pnams = departments.Where(d => pids.Contains(d.Id)).ToList().Select(d => d.Name).ToArray();
var fullName = string.Join("/", pnams);
diff --git a/Blog.Core.Api/wwwroot/BlogCore.Data.json/Permission.tsv b/Blog.Core.Api/wwwroot/BlogCore.Data.json/Permission.tsv
index d1a5c3f8..c026f01e 100644
--- a/Blog.Core.Api/wwwroot/BlogCore.Data.json/Permission.tsv
+++ b/Blog.Core.Api/wwwroot/BlogCore.Data.json/Permission.tsv
@@ -2323,28 +2323,28 @@
"Pid": 94,
"Mid": 63
},
- {
- "Id": 114,
- "Code": " ",
- "Name": "推送文字消息",
- "IsButton": 1,
- "IsHide": 0,
- "IskeepAlive": 0,
- "Func": null,
- "OrderSort": 0,
- "Icon": null,
- "Description": null,
- "Enabled": 1,
- "CreateId": 8,
- "CreateBy": "test",
- "CreateTime": "2020-04-23 16:22:11",
- "ModifyId": null,
- "ModifyBy": null,
- "ModifyTime": "2021-09-29 00:00:00",
- "IsDeleted": 0,
- "Pid": 95,
- "Mid": 0
- },
+ //{
+ // "Id": 114,
+ // "Code": " ",
+ // "Name": "推送文字消息",
+ // "IsButton": 1,
+ // "IsHide": 0,
+ // "IskeepAlive": 0,
+ // "Func": null,
+ // "OrderSort": 0,
+ // "Icon": null,
+ // "Description": null,
+ // "Enabled": 1,
+ // "CreateId": 8,
+ // "CreateBy": "test",
+ // "CreateTime": "2020-04-23 16:22:11",
+ // "ModifyId": null,
+ // "ModifyBy": null,
+ // "ModifyTime": "2021-09-29 00:00:00",
+ // "IsDeleted": 0,
+ // "Pid": 95,
+ // "Mid": 0
+ //},
{
"Code": "-",
"Name": "部门权限管理",
diff --git a/Blog.Core.Api/wwwroot/BlogCore.Data.json/RoleModulePermission.tsv b/Blog.Core.Api/wwwroot/BlogCore.Data.json/RoleModulePermission.tsv
index b7923ab4..eb727383 100644
--- a/Blog.Core.Api/wwwroot/BlogCore.Data.json/RoleModulePermission.tsv
+++ b/Blog.Core.Api/wwwroot/BlogCore.Data.json/RoleModulePermission.tsv
@@ -1647,7 +1647,7 @@
"ModifyId": null,
"ModifyBy": null,
"ModifyTime": "\/Date(1546272000000+0800)\/",
- "Id": 128
+ "Id": 228
},
{
"IsDeleted": false,
@@ -1658,7 +1658,7 @@
"RoleId": 6,
"ModuleId": 0,
"PermissionId": 114,
- "Id": 129
+ "Id": 229
},
{
"IsDeleted": false,
@@ -1669,7 +1669,7 @@
"RoleId": 6,
"ModuleId": 66,
"PermissionId": 115,
- "Id": 130
+ "Id": 230
},
{
"IsDeleted": false,
@@ -1680,7 +1680,7 @@
"RoleId": 6,
"ModuleId": 70,
"PermissionId": 120,
- "Id": 131
+ "Id": 231
},
{
"IsDeleted": false,
@@ -1691,7 +1691,7 @@
"RoleId": 6,
"ModuleId": 66,
"PermissionId": 116,
- "Id": 132
+ "Id": 232
},
{
"IsDeleted": false,
@@ -1702,6 +1702,6 @@
"RoleId": 4,
"ModuleId": 72,
"PermissionId": 122,
- "Id": 133
+ "Id": 233
}
]
diff --git a/Blog.Core.Common/DB/Aop/SqlsugarAop.cs b/Blog.Core.Common/DB/Aop/SqlsugarAop.cs
index 3d83b002..c1417a5a 100644
--- a/Blog.Core.Common/DB/Aop/SqlsugarAop.cs
+++ b/Blog.Core.Common/DB/Aop/SqlsugarAop.cs
@@ -1,4 +1,5 @@
-using Blog.Core.Model.Models.RootTkey;
+using Blog.Core.Model;
+using Blog.Core.Model.Models.RootTkey;
using Blog.Core.Model.Tenants;
using SqlSugar;
using System;
@@ -16,6 +17,13 @@ public static void DataExecuting(object oldValue, DataFilterModel entityInfo)
root.Id = SnowFlakeSingle.Instance.NextId();
}
}
+ if (entityInfo.EntityValue is RootEntityTkey rootEntity)
+ {
+ if (rootEntity.Id == 0)
+ {
+ rootEntity.Id = SnowFlakeSingle.Instance.NextId();
+ }
+ }
if (entityInfo.EntityValue is BaseEntity baseEntity)
{
diff --git a/Blog.Core.Common/Helper/RecursionHelper.cs b/Blog.Core.Common/Helper/RecursionHelper.cs
index 9b27a37d..f6f21a38 100644
--- a/Blog.Core.Common/Helper/RecursionHelper.cs
+++ b/Blog.Core.Common/Helper/RecursionHelper.cs
@@ -117,8 +117,8 @@ public static void LoopToAppendChildrenT(List all, T curItem, string paren
public class PermissionTree
{
- public int value { get; set; }
- public int Pid { get; set; }
+ public long value { get; set; }
+ public long Pid { get; set; }
public string label { get; set; }
public int order { get; set; }
public bool isbtn { get; set; }
@@ -139,8 +139,8 @@ public class DepartmentTree
public class NavigationBar
{
- public int id { get; set; }
- public int pid { get; set; }
+ public long id { get; set; }
+ public long pid { get; set; }
public int order { get; set; }
public string name { get; set; }
public bool IsHide { get; set; } = false;
@@ -165,8 +165,8 @@ public class NavigationBarMeta
public class NavigationBarPro
{
- public int id { get; set; }
- public int parentId { get; set; }
+ public long id { get; set; }
+ public long parentId { get; set; }
public int order { get; set; }
public string name { get; set; }
public bool IsHide { get; set; } = false;
diff --git a/Blog.Core.Common/Seed/DBSeed.cs b/Blog.Core.Common/Seed/DBSeed.cs
index 7b594109..94893c38 100644
--- a/Blog.Core.Common/Seed/DBSeed.cs
+++ b/Blog.Core.Common/Seed/DBSeed.cs
@@ -175,7 +175,11 @@ public static async Task SeedAsync(MyContext myContext, string WebRootPath)
{
var data = JsonConvert.DeserializeObject>(FileHelper.ReadFile(string.Format(SeedDataFolder, "Permission"), Encoding.UTF8), setting);
- myContext.GetEntityDB().InsertRange(data);
+ foreach (var item in data)
+ {
+ Console.WriteLine($"{item.Name}:{item.Id}");
+ myContext.GetEntityDB().Insert(item);
+ }
Console.WriteLine("Table:Permission created success!");
}
else
@@ -190,10 +194,10 @@ public static async Task SeedAsync(MyContext myContext, string WebRootPath)
if (!await myContext.Db.Queryable().AnyAsync())
{
- //var data = JsonConvert.DeserializeObject>(FileHelper.ReadFile(string.Format(SeedDataFolder, "Role"), Encoding.UTF8), setting);
- using var stream = new FileStream(Path.Combine(WebRootPath, "BlogCore.Data.excel", "Role.xlsx"), FileMode.Open);
- var result = await importer.Import(stream);
- var data = result.Data.ToList();
+ var data = JsonConvert.DeserializeObject>(FileHelper.ReadFile(string.Format(SeedDataFolder, "Role"), Encoding.UTF8), setting);
+ //using var stream = new FileStream(Path.Combine(WebRootPath, "BlogCore.Data.excel", "Role.xlsx"), FileMode.Open);
+ //var result = await importer.Import(stream);
+ //var data = result.Data.ToList();
myContext.GetEntityDB().InsertRange(data);
Console.WriteLine("Table:Role created success!");
@@ -212,7 +216,11 @@ public static async Task SeedAsync(MyContext myContext, string WebRootPath)
{
var data = JsonConvert.DeserializeObject>(FileHelper.ReadFile(string.Format(SeedDataFolder, "RoleModulePermission"), Encoding.UTF8), setting);
- myContext.GetEntityDB().InsertRange(data);
+ foreach (var item in data)
+ {
+ Console.WriteLine($"{item.Id}");
+ myContext.GetEntityDB().Insert(item);
+ }
Console.WriteLine("Table:RoleModulePermission created success!");
}
else
@@ -261,10 +269,7 @@ public static async Task SeedAsync(MyContext myContext, string WebRootPath)
if (!await myContext.Db.Queryable().AnyAsync())
{
- //var data = JsonConvert.DeserializeObject>(FileHelper.ReadFile(string.Format(SeedDataFolder, "UserRole"), Encoding.UTF8), setting);
- using var stream = new FileStream(Path.Combine(WebRootPath, "BlogCore.Data.excel", "UserRole.xlsx"), FileMode.Open);
- var result = await importer.Import(stream);
- var data = result.Data.ToList();
+ var data = JsonConvert.DeserializeObject>(FileHelper.ReadFile(string.Format(SeedDataFolder, "UserRole"), Encoding.UTF8), setting);
myContext.GetEntityDB().InsertRange(data);
Console.WriteLine("Table:UserRole created success!");
@@ -281,10 +286,7 @@ public static async Task SeedAsync(MyContext myContext, string WebRootPath)
if (!await myContext.Db.Queryable().AnyAsync())
{
- //var data = JsonConvert.DeserializeObject>(FileHelper.ReadFile(string.Format(SeedDataFolder, "sysUserInfo"), Encoding.UTF8), setting);
- using var stream = new FileStream(Path.Combine(WebRootPath, "BlogCore.Data.excel", "SysUserInfo.xlsx"), FileMode.Open);
- var result = await importer.Import(stream);
- var data = result.Data.ToList();
+ var data = JsonConvert.DeserializeObject>(FileHelper.ReadFile(string.Format(SeedDataFolder, "sysUserInfo"), Encoding.UTF8), setting);
myContext.GetEntityDB().InsertRange(data);
Console.WriteLine("Table:sysUserInfo created success!");
diff --git a/Blog.Core.IServices/IRoleModulePermissionServices.cs b/Blog.Core.IServices/IRoleModulePermissionServices.cs
index 22532479..2a5c7345 100644
--- a/Blog.Core.IServices/IRoleModulePermissionServices.cs
+++ b/Blog.Core.IServices/IRoleModulePermissionServices.cs
@@ -21,6 +21,6 @@ public interface IRoleModulePermissionServices :IBaseServices˵
/// ӿ
///
- Task UpdateModuleId(int permissionId, int moduleId);
+ Task UpdateModuleId(long permissionId, long moduleId);
}
}
diff --git a/Blog.Core.Model/Models/AccessTrendLog.cs b/Blog.Core.Model/Models/AccessTrendLog.cs
index 4a87b13e..fd6dbae7 100644
--- a/Blog.Core.Model/Models/AccessTrendLog.cs
+++ b/Blog.Core.Model/Models/AccessTrendLog.cs
@@ -6,7 +6,7 @@ namespace Blog.Core.Model.Models
///
/// 用户访问趋势日志
///
- public class AccessTrendLog : RootEntityTkey
+ public class AccessTrendLog : RootEntityTkey
{
///
/// 用户
diff --git a/Blog.Core.Model/Models/Advertisement.cs b/Blog.Core.Model/Models/Advertisement.cs
index c2babd74..3b11b21f 100644
--- a/Blog.Core.Model/Models/Advertisement.cs
+++ b/Blog.Core.Model/Models/Advertisement.cs
@@ -3,7 +3,7 @@
namespace Blog.Core.Model.Models
{
- public class Advertisement : RootEntityTkey
+ public class Advertisement : RootEntityTkey
{
///
diff --git a/Blog.Core.Model/Models/BlogArticle.cs b/Blog.Core.Model/Models/BlogArticle.cs
index 66f05bdf..8b75c8df 100644
--- a/Blog.Core.Model/Models/BlogArticle.cs
+++ b/Blog.Core.Model/Models/BlogArticle.cs
@@ -13,8 +13,8 @@ public class BlogArticle
/// 主键
///
/// 这里之所以没用RootEntity,是想保持和之前的数据库一致,主键是bID,不是Id
- [SugarColumn(IsNullable = false, IsPrimaryKey = true, IsIdentity = true)]
- public int bID { get; set; }
+ [SugarColumn(IsNullable = false, IsPrimaryKey = true, IsIdentity = false)]
+ public long bID { get; set; }
///
/// 创建人
diff --git a/Blog.Core.Model/Models/BlogArticleComment.cs b/Blog.Core.Model/Models/BlogArticleComment.cs
index 08010863..519fb003 100644
--- a/Blog.Core.Model/Models/BlogArticleComment.cs
+++ b/Blog.Core.Model/Models/BlogArticleComment.cs
@@ -7,7 +7,7 @@ namespace Blog.Core.Model.Models;
///
public class BlogArticleComment : RootEntityTkey
{
- public int bID { get; set; }
+ public long bID { get; set; }
public string Comment { get; set; }
diff --git a/Blog.Core.Model/Models/Department.cs b/Blog.Core.Model/Models/Department.cs
index 3583bcff..424bcf44 100644
--- a/Blog.Core.Model/Models/Department.cs
+++ b/Blog.Core.Model/Models/Department.cs
@@ -7,7 +7,7 @@ namespace Blog.Core.Model.Models
///
/// 部门表
///
- public class Department : DepartmentRoot
+ public class Department : DepartmentRoot
{
///
/// Desc:部门关系编码
diff --git a/Blog.Core.Model/Models/GblLogAudit.cs b/Blog.Core.Model/Models/GblLogAudit.cs
index 4b1bd9cd..2cecce8b 100644
--- a/Blog.Core.Model/Models/GblLogAudit.cs
+++ b/Blog.Core.Model/Models/GblLogAudit.cs
@@ -12,8 +12,8 @@ public class GblLogAudit
///
///ID
///
- [SugarColumn(ColumnDescription = "ID", IsNullable = false, IsPrimaryKey = true, IsIdentity = true)]
- public int Id { get; set; }
+ [SugarColumn(ColumnDescription = "ID", IsNullable = false, IsPrimaryKey = true, IsIdentity = false)]
+ public long Id { get; set; }
///
///HttpContext.TraceIdentifier 事件链路ID(获取或设置一个唯一标识符,用于在跟踪日志中表示此请求。)
diff --git a/Blog.Core.Model/Models/Guestbook.cs b/Blog.Core.Model/Models/Guestbook.cs
index d1f671c0..0cd5dcef 100644
--- a/Blog.Core.Model/Models/Guestbook.cs
+++ b/Blog.Core.Model/Models/Guestbook.cs
@@ -3,13 +3,13 @@
namespace Blog.Core.Model.Models
{
- public class Guestbook:RootEntityTkey
+ public class Guestbook : RootEntityTkey
{
-
+
/// 博客ID
///
///
- public int? blogId { get; set; }
+ public long? blogId { get; set; }
/// 创建时间
///
///
diff --git a/Blog.Core.Model/Models/Modules.cs b/Blog.Core.Model/Models/Modules.cs
index b62c0a47..6e41aaac 100644
--- a/Blog.Core.Model/Models/Modules.cs
+++ b/Blog.Core.Model/Models/Modules.cs
@@ -6,7 +6,7 @@ namespace Blog.Core.Model.Models
///
/// 接口API地址信息表
///
- public class Modules : ModulesRoot
+ public class Modules : ModulesRoot
{
public Modules()
{
diff --git a/Blog.Core.Model/Models/OperateLog.cs b/Blog.Core.Model/Models/OperateLog.cs
index 4086781c..3c2fb54c 100644
--- a/Blog.Core.Model/Models/OperateLog.cs
+++ b/Blog.Core.Model/Models/OperateLog.cs
@@ -6,7 +6,7 @@ namespace Blog.Core.Model.Models
///
/// 日志记录
///
- public class OperateLog : RootEntityTkey
+ public class OperateLog : RootEntityTkey
{
///
diff --git a/Blog.Core.Model/Models/PasswordLib.cs b/Blog.Core.Model/Models/PasswordLib.cs
index 2b43c265..b8b633d6 100644
--- a/Blog.Core.Model/Models/PasswordLib.cs
+++ b/Blog.Core.Model/Models/PasswordLib.cs
@@ -7,11 +7,11 @@ namespace Blog.Core.Model.Models
/// 密码库表
///
[SugarTable("PasswordLib", "密码库表")]//('数据库表名','数据库表备注')
- [TenantAttribute("WMBLOG_MYSQL_2")] //('代表是哪个数据库,名字是appsettings.json 的 ConnId')
+ [Tenant("WMBLOG_MYSQL_2")] //('代表是哪个数据库,名字是appsettings.json 的 ConnId')
public class PasswordLib
{
- [SugarColumn(IsNullable = false, IsPrimaryKey = true, IsIdentity = true)]
- public int PLID { get; set; }
+ [SugarColumn(IsNullable = false, IsPrimaryKey = true, IsIdentity = false)]
+ public long PLID { get; set; }
///
///获取或设置是否禁用,逻辑上的删除,非物理删除
diff --git a/Blog.Core.Model/Models/Permission.cs b/Blog.Core.Model/Models/Permission.cs
index c650cb5e..deece0c0 100644
--- a/Blog.Core.Model/Models/Permission.cs
+++ b/Blog.Core.Model/Models/Permission.cs
@@ -7,7 +7,7 @@ namespace Blog.Core.Model.Models
///
/// 路由菜单表
///
- public class Permission : PermissionRoot
+ public class Permission : PermissionRoot
{
public Permission()
{
diff --git a/Blog.Core.Model/Models/Role.cs b/Blog.Core.Model/Models/Role.cs
index e34ccdd9..1357afb0 100644
--- a/Blog.Core.Model/Models/Role.cs
+++ b/Blog.Core.Model/Models/Role.cs
@@ -6,7 +6,7 @@ namespace Blog.Core.Model.Models
///
/// 角色表
///
- public class Role : RootEntityTkey
+ public class Role : RootEntityTkey
{
public Role()
{
diff --git a/Blog.Core.Model/Models/RoleModulePermission.cs b/Blog.Core.Model/Models/RoleModulePermission.cs
index 13d82a80..482b9b4e 100644
--- a/Blog.Core.Model/Models/RoleModulePermission.cs
+++ b/Blog.Core.Model/Models/RoleModulePermission.cs
@@ -6,7 +6,7 @@ namespace Blog.Core.Model.Models
///
/// 按钮跟权限关联表
///
- public class RoleModulePermission : RoleModulePermissionRoot
+ public class RoleModulePermission : RoleModulePermissionRoot
{
public RoleModulePermission()
{
diff --git a/Blog.Core.Model/Models/RootEntity.cs b/Blog.Core.Model/Models/RootEntity.cs
deleted file mode 100644
index d3874bb4..00000000
--- a/Blog.Core.Model/Models/RootEntity.cs
+++ /dev/null
@@ -1,15 +0,0 @@
-using SqlSugar;
-
-namespace Blog.Core.Model
-{
- public class RootEntity
- {
- ///
- /// ID
- ///
- [SugarColumn(IsNullable = false, IsPrimaryKey = true)]
- public int Id { get; set; }
-
-
- }
-}
\ No newline at end of file
diff --git a/Blog.Core.Model/Models/TasksLog.cs b/Blog.Core.Model/Models/TasksLog.cs
index b4317c95..c79e8077 100644
--- a/Blog.Core.Model/Models/TasksLog.cs
+++ b/Blog.Core.Model/Models/TasksLog.cs
@@ -6,12 +6,12 @@ namespace Blog.Core.Model.Models
///
/// 任务日志表
///
- public class TasksLog : RootEntityTkey
+ public class TasksLog : RootEntityTkey
{
///
/// 任务ID
///
- public int JobId { get; set; }
+ public long JobId { get; set; }
///
/// 任务耗时
///
diff --git a/Blog.Core.Model/Models/TasksQz.cs b/Blog.Core.Model/Models/TasksQz.cs
index 1c07b60e..b029a995 100644
--- a/Blog.Core.Model/Models/TasksQz.cs
+++ b/Blog.Core.Model/Models/TasksQz.cs
@@ -8,7 +8,7 @@ namespace Blog.Core.Model.Models
///
/// 任务计划表
///
- public class TasksQz : RootEntityTkey
+ public class TasksQz : RootEntityTkey
{
///
/// 任务名称
diff --git a/Blog.Core.Model/Models/TestModels.cs b/Blog.Core.Model/Models/TestModels.cs
index f5fa7dc7..8a8d123c 100644
--- a/Blog.Core.Model/Models/TestModels.cs
+++ b/Blog.Core.Model/Models/TestModels.cs
@@ -5,9 +5,9 @@ public class TestMuchTableResult
{
public string moduleName { get; set; }
public string permName { get; set; }
- public int rid { get; set; }
- public int mid { get; set; }
- public int? pid { get; set; }
+ public long rid { get; set; }
+ public long mid { get; set; }
+ public long? pid { get; set; }
}
}
diff --git a/Blog.Core.Model/Models/Topic.cs b/Blog.Core.Model/Models/Topic.cs
index 16bf7dad..e57bd561 100644
--- a/Blog.Core.Model/Models/Topic.cs
+++ b/Blog.Core.Model/Models/Topic.cs
@@ -7,7 +7,7 @@ namespace Blog.Core.Model.Models
///
/// Tibug 类别
///
- public class Topic : RootEntityTkey
+ public class Topic : RootEntityTkey
{
public Topic()
{
diff --git a/Blog.Core.Model/Models/TopicDetail.cs b/Blog.Core.Model/Models/TopicDetail.cs
index 87e16ebf..1a98f3af 100644
--- a/Blog.Core.Model/Models/TopicDetail.cs
+++ b/Blog.Core.Model/Models/TopicDetail.cs
@@ -6,7 +6,7 @@ namespace Blog.Core.Model.Models
///
/// Tibug 博文
///
- public class TopicDetail : TopicDetailRoot
+ public class TopicDetail : TopicDetailRoot
{
public TopicDetail()
{
diff --git a/Blog.Core.Model/Models/UserRole.cs b/Blog.Core.Model/Models/UserRole.cs
index 996eea2c..7ed9c6be 100644
--- a/Blog.Core.Model/Models/UserRole.cs
+++ b/Blog.Core.Model/Models/UserRole.cs
@@ -6,11 +6,11 @@ namespace Blog.Core.Model.Models
///
/// 用户跟角色关联表
///
- public class UserRole : UserRoleRoot
+ public class UserRole : UserRoleRoot
{
public UserRole() { }
- public UserRole(int uid, int rid)
+ public UserRole(long uid, long rid)
{
UserId = uid;
RoleId = rid;
@@ -31,7 +31,7 @@ public UserRole(int uid, int rid)
/// 创建ID
///
[SugarColumn(IsNullable = true)]
- public int? CreateId { get; set; }
+ public long? CreateId { get; set; }
///
/// 创建者
///
diff --git a/Blog.Core.Model/Models/sysUserInfo.cs b/Blog.Core.Model/Models/sysUserInfo.cs
index 366b2291..2a417a16 100644
--- a/Blog.Core.Model/Models/sysUserInfo.cs
+++ b/Blog.Core.Model/Models/sysUserInfo.cs
@@ -9,7 +9,7 @@ namespace Blog.Core.Model.Models
///
//[SugarTable("SysUserInfo")]
[SugarTable("SysUserInfo", "用户表")] //('数据库表名','数据库表备注')
- public class SysUserInfo : SysUserInfoRoot
+ public class SysUserInfo : SysUserInfoRoot
{
public SysUserInfo()
{
@@ -133,7 +133,7 @@ public SysUserInfo(string loginName, string loginPWD)
public List RoleNames { get; set; }
[SugarColumn(IsIgnore = true)]
- public List Dids { get; set; }
+ public List Dids { get; set; }
[SugarColumn(IsIgnore = true)]
public string DepartmentName { get; set; }
diff --git a/Blog.Core.Model/ViewModels/BlogViewModels.cs b/Blog.Core.Model/ViewModels/BlogViewModels.cs
index f959270c..411a8ef7 100644
--- a/Blog.Core.Model/ViewModels/BlogViewModels.cs
+++ b/Blog.Core.Model/ViewModels/BlogViewModels.cs
@@ -34,7 +34,7 @@ public class BlogViewModels
///
/// 上一篇id
///
- public int previousID { get; set; }
+ public long previousID { get; set; }
///
/// 下一篇
@@ -44,7 +44,7 @@ public class BlogViewModels
///
/// 下一篇id
///
- public int nextID { get; set; }
+ public long nextID { get; set; }
/// 类别
///
diff --git a/Blog.Core.Repository/IRoleModulePermissionRepository.cs b/Blog.Core.Repository/IRoleModulePermissionRepository.cs
index c66448f0..9ba3d4ed 100644
--- a/Blog.Core.Repository/IRoleModulePermissionRepository.cs
+++ b/Blog.Core.Repository/IRoleModulePermissionRepository.cs
@@ -19,6 +19,6 @@ public interface IRoleModulePermissionRepository : IBaseRepository菜单主键
/// 接口主键
///
- Task UpdateModuleId(int permissionId, int moduleId);
+ Task UpdateModuleId(long permissionId, long moduleId);
}
}
diff --git a/Blog.Core.Repository/RoleModulePermissionRepository.cs b/Blog.Core.Repository/RoleModulePermissionRepository.cs
index 1cb21ebf..9438ff50 100644
--- a/Blog.Core.Repository/RoleModulePermissionRepository.cs
+++ b/Blog.Core.Repository/RoleModulePermissionRepository.cs
@@ -99,7 +99,7 @@ public async Task> GetRMPMapsPage()
/// 菜单主键
/// 接口主键
///
- public async Task UpdateModuleId(int permissionId, int moduleId)
+ public async Task UpdateModuleId(long permissionId, long moduleId)
{
await Db.Updateable(it => it.ModuleId == moduleId).Where(
it => it.PermissionId == permissionId).ExecuteCommandAsync();
diff --git a/Blog.Core.Services/RoleModulePermissionServices.cs b/Blog.Core.Services/RoleModulePermissionServices.cs
index c0248e17..d3834f89 100644
--- a/Blog.Core.Services/RoleModulePermissionServices.cs
+++ b/Blog.Core.Services/RoleModulePermissionServices.cs
@@ -83,7 +83,7 @@ public async Task> GetRMPMaps()
/// 菜单主键
/// 接口主键
///
- public async Task UpdateModuleId(int permissionId, int moduleId)
+ public async Task UpdateModuleId(long permissionId, long moduleId)
{
await _dal.UpdateModuleId(permissionId, moduleId);
}
From 0ed67675a6bbab5a1b997ed9ea002f60aa3fde32 Mon Sep 17 00:00:00 2001
From: hudingwen <765472804@qq.com>
Date: Fri, 31 Mar 2023 22:02:30 +0800
Subject: [PATCH 09/84] =?UTF-8?q?=E6=9D=83=E9=99=90=E5=88=86=E9=85=8D?=
=?UTF-8?q?=E4=BF=9D=E5=AD=98=E9=80=BB=E8=BE=91=E4=BC=98=E5=8C=96=20sqlsug?=
=?UTF-8?q?arAop=E9=80=BB=E8=BE=91=E5=AE=8C=E5=96=84?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
Blog.Core.Api/Blog.Core.xml | 3 +-
.../Controllers/PermissionController.cs | 79 +++++++++----------
Blog.Core.Common/DB/Aop/SqlsugarAop.cs | 41 ++++++++++
3 files changed, 81 insertions(+), 42 deletions(-)
diff --git a/Blog.Core.Api/Blog.Core.xml b/Blog.Core.Api/Blog.Core.xml
index c0b52222..79325e37 100644
--- a/Blog.Core.Api/Blog.Core.xml
+++ b/Blog.Core.Api/Blog.Core.xml
@@ -361,7 +361,7 @@
菜单管理
-
+
构造函数
@@ -369,6 +369,7 @@
+
diff --git a/Blog.Core.Api/Controllers/PermissionController.cs b/Blog.Core.Api/Controllers/PermissionController.cs
index 9277a36b..f4889c73 100644
--- a/Blog.Core.Api/Controllers/PermissionController.cs
+++ b/Blog.Core.Api/Controllers/PermissionController.cs
@@ -6,6 +6,8 @@
using Blog.Core.IServices;
using Blog.Core.Model;
using Blog.Core.Model.Models;
+using Blog.Core.Repository.UnitOfWorks;
+using Blog.Core.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
@@ -21,6 +23,7 @@ namespace Blog.Core.Controllers
[Authorize(Permissions.Name)]
public class PermissionController : BaseApiController
{
+ readonly IUnitOfWorkManage _unitOfWorkManage;
readonly IPermissionServices _permissionServices;
readonly IModuleServices _moduleServices;
readonly IRoleModulePermissionServices _roleModulePermissionServices;
@@ -37,16 +40,19 @@ public class PermissionController : BaseApiController
///
///
///
+ ///
///
///
///
///
public PermissionController(IPermissionServices permissionServices, IModuleServices moduleServices,
IRoleModulePermissionServices roleModulePermissionServices, IUserRoleServices userRoleServices,
+ IUnitOfWorkManage unitOfWorkManage,
IHttpClientFactory httpClientFactory,
IHttpContextAccessor httpContext, IUser user, PermissionRequirement requirement)
{
_permissionServices = permissionServices;
+ _unitOfWorkManage = unitOfWorkManage;
_moduleServices = moduleServices;
_roleModulePermissionServices = roleModulePermissionServices;
_userRoleServices = userRoleServices;
@@ -239,25 +245,24 @@ public async Task> Post([FromBody] Permission permission)
///
[HttpPost]
public async Task> Assign([FromBody] AssignView assignView)
- {
- var data = new MessageModel();
-
-
+ {
if (assignView.rid > 0)
{
- data.success = true;
-
- var roleModulePermissions = await _roleModulePermissionServices.Query(d => d.RoleId == assignView.rid);
+ //开启事务
+ try
+ {
+ var old_rmps = await _roleModulePermissionServices.Query(d => d.RoleId == assignView.rid);
- var remove = roleModulePermissions.Where(d => !assignView.pids.Contains(d.PermissionId.ObjToInt())).Select(c => (object)c.Id);
- data.success &= remove.Any() ? await _roleModulePermissionServices.DeleteByIds(remove.ToArray()) : true;
+ _unitOfWorkManage.BeginTran();
+ await _permissionServices.Db.Deleteable(t => t.RoleId == assignView.rid).ExecuteCommandAsync();
+ var permissions = await _permissionServices.Query(d => d.IsDeleted == false);
- foreach (var item in assignView.pids)
- {
- var rmpitem = roleModulePermissions.Where(d => d.PermissionId == item);
- var moduleid = (await _permissionServices.Query(p => p.Id == item)).FirstOrDefault()?.Mid;
- if (!rmpitem.Any())
+ List new_rmps = new List();
+ var nowTime = _permissionServices.Db.GetDate();
+ foreach (var item in assignView.pids)
{
+ var moduleid = permissions.Find(p => p.Id == item)?.Mid;
+ var find_old_rmps = old_rmps.Find(p => p.PermissionId == item);
RoleModulePermission roleModulePermission = new RoleModulePermission()
{
@@ -265,39 +270,31 @@ public async Task> Assign([FromBody] AssignView assignView)
RoleId = assignView.rid,
ModuleId = moduleid.ObjToInt(),
PermissionId = item,
- };
-
+ CreateId = find_old_rmps == null ? _user.ID : find_old_rmps.CreateId,
+ CreateBy = find_old_rmps == null ? _user.Name : find_old_rmps.CreateBy,
+ CreateTime = find_old_rmps == null ? nowTime : find_old_rmps.CreateTime,
+ ModifyId = _user.ID,
+ ModifyBy = _user.Name,
+ ModifyTime = nowTime
- roleModulePermission.CreateId = _user.ID;
- roleModulePermission.CreateBy = _user.Name;
-
- data.success &= (await _roleModulePermissionServices.Add(roleModulePermission)) > 0;
-
- }
- else
- {
- foreach (var role in rmpitem)
- {
- if (!role.ModuleId.Equals(moduleid))
- {
- role.ModuleId = moduleid.Value;
- await _roleModulePermissionServices.Update(role, new List { "ModuleId" });
- }
- }
+ };
+ new_rmps.Add(roleModulePermission);
}
+ if(new_rmps.Count>0) await _roleModulePermissionServices.Add(new_rmps);
+ _unitOfWorkManage.CommitTran();
}
-
- if (data.success)
+ catch (Exception)
{
- _requirement.Permissions.Clear();
- data.response = "";
- data.msg = "保存成功";
+ _unitOfWorkManage.RollbackTran();
+ throw;
}
-
+ _requirement.Permissions.Clear();
+ return Success("保存成功");
}
-
-
- return data;
+ else
+ {
+ return Failed("请选择要操作的角色");
+ }
}
diff --git a/Blog.Core.Common/DB/Aop/SqlsugarAop.cs b/Blog.Core.Common/DB/Aop/SqlsugarAop.cs
index c1417a5a..c70d9283 100644
--- a/Blog.Core.Common/DB/Aop/SqlsugarAop.cs
+++ b/Blog.Core.Common/DB/Aop/SqlsugarAop.cs
@@ -1,6 +1,7 @@
using Blog.Core.Model;
using Blog.Core.Model.Models.RootTkey;
using Blog.Core.Model.Tenants;
+using NetTaste;
using SqlSugar;
using System;
@@ -69,6 +70,46 @@ public static void DataExecuting(object oldValue, DataFilterModel entityInfo)
}
}
}
+ else
+ {
+ //兼容以前的表
+ var getType = entityInfo.EntityValue.GetType();
+
+
+ switch (entityInfo.OperationType)
+ {
+
+ case DataFilterType.InsertByObject:
+ var dyCreateBy = getType.GetProperty("CreateBy");
+ var dyCreateId = getType.GetProperty("CreateId");
+ var dyCreateTime = getType.GetProperty("CreateTime");
+
+ if (App.User?.ID > 0 && dyCreateBy != null && dyCreateBy.GetValue(entityInfo.EntityValue) == null)
+ dyCreateBy.SetValue(entityInfo.EntityValue, App.User.Name);
+
+ if (App.User?.ID > 0 && dyCreateId != null && dyCreateId.GetValue(entityInfo.EntityValue) == null)
+ dyCreateId.SetValue(entityInfo.EntityValue, App.User.ID);
+
+ if (dyCreateTime != null && (DateTime)dyCreateTime.GetValue(entityInfo.EntityValue) == DateTime.MinValue)
+ dyCreateTime.SetValue(entityInfo.EntityValue, DateTime.Now);
+
+ break;
+ case DataFilterType.UpdateByObject:
+ var dyModifyBy = getType.GetProperty("ModifyBy");
+ var dyModifyId = getType.GetProperty("ModifyId");
+ var dyModifyTime = getType.GetProperty("ModifyTime");
+
+ if (App.User?.ID > 0 && dyModifyBy != null)
+ dyModifyBy.SetValue(entityInfo.EntityValue, App.User.Name);
+
+ if (App.User?.ID > 0 && dyModifyId != null)
+ dyModifyId.SetValue(entityInfo.EntityValue, App.User.ID);
+
+ if (dyModifyTime != null)
+ dyModifyTime.SetValue(entityInfo.EntityValue, DateTime.Now);
+ break;
+ }
+ }
}
private static string GetWholeSql(SugarParameter[] paramArr, string sql)
From 3c0d9f977cc03da275ba7d32a4f27e083b947ce3 Mon Sep 17 00:00:00 2001
From: hudingwen <765472804@qq.com>
Date: Sat, 1 Apr 2023 21:09:47 +0800
Subject: [PATCH 10/84] =?UTF-8?q?=E6=B7=BB=E5=8A=A0update=20list?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
Blog.Core.IServices/BASE/IBaseServices.cs | 1 +
Blog.Core.Repository/BASE/BaseRepository.cs | 9 +++++++++
Blog.Core.Repository/BASE/IBaseRepository.cs | 6 ++++++
Blog.Core.Services/BASE/BaseServices.cs | 9 +++++++++
4 files changed, 25 insertions(+)
diff --git a/Blog.Core.IServices/BASE/IBaseServices.cs b/Blog.Core.IServices/BASE/IBaseServices.cs
index 4091b978..b491614f 100644
--- a/Blog.Core.IServices/BASE/IBaseServices.cs
+++ b/Blog.Core.IServices/BASE/IBaseServices.cs
@@ -27,6 +27,7 @@ public interface IBaseServices where TEntity : class
Task DeleteByIds(object[] ids);
Task Update(TEntity model);
+ Task Update(List model);
Task Update(TEntity entity, string where);
Task Update(object operateAnonymousObjects);
diff --git a/Blog.Core.Repository/BASE/BaseRepository.cs b/Blog.Core.Repository/BASE/BaseRepository.cs
index 3048baa8..9ef11ecd 100644
--- a/Blog.Core.Repository/BASE/BaseRepository.cs
+++ b/Blog.Core.Repository/BASE/BaseRepository.cs
@@ -170,6 +170,15 @@ public async Task Update(TEntity entity)
//这种方式会以主键为条件
return await _db.Updateable(entity).ExecuteCommandHasChangeAsync();
}
+ ///
+ /// 更新实体数据
+ ///
+ /// 博文实体类
+ ///
+ public async Task Update(List entity)
+ {
+ return await _db.Updateable(entity).ExecuteCommandHasChangeAsync();
+ }
public async Task Update(TEntity entity, string where)
{
diff --git a/Blog.Core.Repository/BASE/IBaseRepository.cs b/Blog.Core.Repository/BASE/IBaseRepository.cs
index 5f70a4be..8ef05c1e 100644
--- a/Blog.Core.Repository/BASE/IBaseRepository.cs
+++ b/Blog.Core.Repository/BASE/IBaseRepository.cs
@@ -69,6 +69,12 @@ public interface IBaseRepository where TEntity : class
///
///
Task Update(TEntity model);
+ ///
+ /// 更新model
+ ///
+ ///
+ ///
+ Task Update(List model);
///
/// 根据model,更新,带where条件
diff --git a/Blog.Core.Services/BASE/BaseServices.cs b/Blog.Core.Services/BASE/BaseServices.cs
index 7ee55eb1..14f69636 100644
--- a/Blog.Core.Services/BASE/BaseServices.cs
+++ b/Blog.Core.Services/BASE/BaseServices.cs
@@ -80,6 +80,15 @@ public async Task Update(TEntity entity)
{
return await BaseDal.Update(entity);
}
+ ///
+ /// 更新实体数据
+ ///
+ /// 博文实体类
+ ///
+ public async Task Update(List entity)
+ {
+ return await BaseDal.Update(entity);
+ }
public async Task Update(TEntity entity, string where)
{
From f785d507704275c104a61e8793548644084983ed Mon Sep 17 00:00:00 2001
From: "Lemon.NoCry" <773596523@qq.com>
Date: Sat, 1 Apr 2023 21:29:34 +0800
Subject: [PATCH 11/84] =?UTF-8?q?=F0=9F=8E=A8=20=E4=BC=98=E5=8C=96?=
=?UTF-8?q?=E9=9B=AA=E8=8A=B1id=E4=BD=BF=E7=94=A8?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
Blog.Core.Api/Blog.Core.Model.xml | 5 ----
.../Controllers/PermissionController.cs | 4 +--
Blog.Core.Common/DB/Aop/SqlsugarAop.cs | 15 ++++------
Blog.Core.IServices/BASE/IBaseServices.cs | 4 +--
Blog.Core.Model/Models/RootTkey/BaseEntity.cs | 8 +-----
Blog.Core.Repository/BASE/BaseRepository.cs | 28 +++++++++++--------
Blog.Core.Repository/BASE/IBaseRepository.cs | 4 +--
Blog.Core.Services/BASE/BaseServices.cs | 11 ++++++--
8 files changed, 37 insertions(+), 42 deletions(-)
diff --git a/Blog.Core.Api/Blog.Core.Model.xml b/Blog.Core.Api/Blog.Core.Model.xml
index fe62d8e2..79666d28 100644
--- a/Blog.Core.Api/Blog.Core.Model.xml
+++ b/Blog.Core.Api/Blog.Core.Model.xml
@@ -832,11 +832,6 @@
修改时间
-
-
- 雪花Id
-
-
状态
diff --git a/Blog.Core.Api/Controllers/PermissionController.cs b/Blog.Core.Api/Controllers/PermissionController.cs
index f4889c73..059e9b18 100644
--- a/Blog.Core.Api/Controllers/PermissionController.cs
+++ b/Blog.Core.Api/Controllers/PermissionController.cs
@@ -754,11 +754,11 @@ public async Task>> MigratePermission(string actio
List modules = await _moduleServices.Query(d => d.LinkUrl != null && d.LinkUrl.ToLower() == item.Module.LinkUrl);
if (!modules.Any())
{
- int mid = await _moduleServices.Add(item.Module);
+ var mid = await _moduleServices.Add(item.Module);
if (mid > 0)
{
item.Mid = mid;
- int permissionid = await _permissionServices.Add(item);
+ var permissionid = await _permissionServices.Add(item);
}
}
diff --git a/Blog.Core.Common/DB/Aop/SqlsugarAop.cs b/Blog.Core.Common/DB/Aop/SqlsugarAop.cs
index c70d9283..9ab494a4 100644
--- a/Blog.Core.Common/DB/Aop/SqlsugarAop.cs
+++ b/Blog.Core.Common/DB/Aop/SqlsugarAop.cs
@@ -1,7 +1,6 @@
using Blog.Core.Model;
using Blog.Core.Model.Models.RootTkey;
using Blog.Core.Model.Tenants;
-using NetTaste;
using SqlSugar;
using System;
@@ -11,13 +10,6 @@ public static class SqlSugarAop
{
public static void DataExecuting(object oldValue, DataFilterModel entityInfo)
{
- if (entityInfo.EntityValue is BaseEntity root)
- {
- if (root.Id == 0)
- {
- root.Id = SnowFlakeSingle.Instance.NextId();
- }
- }
if (entityInfo.EntityValue is RootEntityTkey rootEntity)
{
if (rootEntity.Id == 0)
@@ -73,12 +65,15 @@ public static void DataExecuting(object oldValue, DataFilterModel entityInfo)
else
{
//兼容以前的表
- var getType = entityInfo.EntityValue.GetType();
+ //这里要小心 在AOP里用反射 数据量多性能就会有问题
+ //要么都统一使用基类
+ //要么考虑老的表没必要兼容老的表
+ //
+ var getType = entityInfo.EntityValue.GetType();
switch (entityInfo.OperationType)
{
-
case DataFilterType.InsertByObject:
var dyCreateBy = getType.GetProperty("CreateBy");
var dyCreateId = getType.GetProperty("CreateId");
diff --git a/Blog.Core.IServices/BASE/IBaseServices.cs b/Blog.Core.IServices/BASE/IBaseServices.cs
index 4091b978..21f1afb4 100644
--- a/Blog.Core.IServices/BASE/IBaseServices.cs
+++ b/Blog.Core.IServices/BASE/IBaseServices.cs
@@ -16,9 +16,9 @@ public interface IBaseServices where TEntity : class
Task QueryById(object objId, bool blnUseCache = false);
Task> QueryByIDs(object[] lstIds);
- Task Add(TEntity model);
+ Task Add(TEntity model);
- Task Add(List listEntity);
+ Task> Add(List listEntity);
Task DeleteById(object id);
diff --git a/Blog.Core.Model/Models/RootTkey/BaseEntity.cs b/Blog.Core.Model/Models/RootTkey/BaseEntity.cs
index efbde8fd..b6dabe54 100644
--- a/Blog.Core.Model/Models/RootTkey/BaseEntity.cs
+++ b/Blog.Core.Model/Models/RootTkey/BaseEntity.cs
@@ -4,14 +4,8 @@
namespace Blog.Core.Model.Models.RootTkey;
-public class BaseEntity : IDeleteFilter
+public class BaseEntity : RootEntityTkey, IDeleteFilter
{
- ///
- /// 雪花Id
- ///
- [SugarColumn(IsNullable = false, IsPrimaryKey = true, IsIdentity = false)]
- public long Id { get; set; }
-
#region 数据状态管理
///
diff --git a/Blog.Core.Repository/BASE/BaseRepository.cs b/Blog.Core.Repository/BASE/BaseRepository.cs
index 3048baa8..e808690d 100644
--- a/Blog.Core.Repository/BASE/BaseRepository.cs
+++ b/Blog.Core.Repository/BASE/BaseRepository.cs
@@ -114,7 +114,7 @@ public async Task> QueryByIDs(object[] lstIds)
///
/// 博文实体类
///
- public async Task Add(TEntity entity)
+ public async Task Add(TEntity entity)
{
//var i = await Task.Run(() => _db.Insertable(entity).ExecuteReturnBigIdentity());
////返回的i是long类型,这里你可以根据你的业务需要进行处理
@@ -125,7 +125,7 @@ public async Task Add(TEntity entity)
//这里你可以返回TEntity,这样的话就可以获取id值,无论主键是什么类型
//var return3 = await insert.ExecuteReturnEntityAsync();
- return await insert.ExecuteReturnIdentityAsync();
+ return await insert.ExecuteReturnSnowflakeIdAsync();
}
///
@@ -134,16 +134,16 @@ public async Task Add(TEntity entity)
/// 实体类
/// 指定只插入列
/// 返回自增量列
- public async Task Add(TEntity entity, Expression> insertColumns = null)
+ public async Task Add(TEntity entity, Expression> insertColumns = null)
{
var insert = _db.Insertable(entity);
if (insertColumns == null)
{
- return await insert.ExecuteReturnIdentityAsync();
+ return await insert.ExecuteReturnSnowflakeIdAsync();
}
else
{
- return await insert.InsertColumns(insertColumns).ExecuteReturnIdentityAsync();
+ return await insert.InsertColumns(insertColumns).ExecuteReturnSnowflakeIdAsync();
}
}
@@ -152,9 +152,9 @@ public async Task Add(TEntity entity, Expression> ins
///
/// 实体集合
/// 影响行数
- public async Task Add(List listEntity)
+ public async Task> Add(List listEntity)
{
- return await _db.Insertable(listEntity.ToArray()).ExecuteCommandAsync();
+ return await _db.Insertable(listEntity.ToArray()).ExecuteReturnSnowflakeIdListAsync();
}
///
@@ -557,7 +557,9 @@ public async Task> QueryTabsPage(
// groupName = s.groupName,
// jobName = s.jobName
// }, exp, s => new { s.uID, s.uRealName, s.groupName, s.jobName }, model.currentPage, model.pageSize, model.orderField + " " + model.orderType);
+
#region Split分表基础接口 (基础CRUD)
+
///
/// 分页查询[使用版本,其他分页未测试]
///
@@ -573,9 +575,10 @@ public async Task> QueryPageSplit(Expression(pageIndex, totalCount, pageSize, list);
+ var data = new PageModel(pageIndex, totalCount, pageSize, list);
return data;
}
+
///
/// 写入实体数据
///
@@ -599,24 +602,26 @@ public async Task UpdateSplit(TEntity entity, DateTime dateTime)
//return await _db.Updateable(entity).SplitTable().ExecuteCommandAsync();//,SplitTable不能少
//精准找单个表
- var tableName = _db.SplitHelper().GetTableName(dateTime);//根据时间获取表名
+ var tableName = _db.SplitHelper().GetTableName(dateTime); //根据时间获取表名
return await _db.Updateable(entity).AS(tableName).ExecuteCommandHasChangeAsync();
}
+
///
/// 删除数据
///
///
///
///
- public async Task DeleteSplit(TEntity entity,DateTime dateTime)
+ public async Task DeleteSplit(TEntity entity, DateTime dateTime)
{
////直接根据实体集合删除 (全自动 找表插入),返回受影响数
//return await _db.Deleteable(entity).SplitTable().ExecuteCommandAsync();//,SplitTable不能少
//精准找单个表
- var tableName = _db.SplitHelper().GetTableName(dateTime);//根据时间获取表名
+ var tableName = _db.SplitHelper().GetTableName(dateTime); //根据时间获取表名
return await _db.Deleteable().AS(tableName).Where(entity).ExecuteCommandHasChangeAsync();
}
+
///
/// 根据ID查找数据
///
@@ -626,6 +631,7 @@ public async Task QueryByIdSplit(object objId)
{
return await _db.Queryable().In(objId).SplitTable(tabs => tabs).SingleAsync();
}
+
#endregion
}
}
\ No newline at end of file
diff --git a/Blog.Core.Repository/BASE/IBaseRepository.cs b/Blog.Core.Repository/BASE/IBaseRepository.cs
index 5f70a4be..e3e6553b 100644
--- a/Blog.Core.Repository/BASE/IBaseRepository.cs
+++ b/Blog.Core.Repository/BASE/IBaseRepository.cs
@@ -33,14 +33,14 @@ public interface IBaseRepository where TEntity : class
///
///
///
- Task Add(TEntity model);
+ Task Add(TEntity model);
///
/// 批量添加
///
///
///
- Task Add(List listEntity);
+ Task> Add(List listEntity);
///
/// 根据id 删除某一实体
diff --git a/Blog.Core.Services/BASE/BaseServices.cs b/Blog.Core.Services/BASE/BaseServices.cs
index 7ee55eb1..809890fb 100644
--- a/Blog.Core.Services/BASE/BaseServices.cs
+++ b/Blog.Core.Services/BASE/BaseServices.cs
@@ -56,7 +56,7 @@ public async Task> QueryByIDs(object[] lstIds)
///
/// 博文实体类
///
- public async Task Add(TEntity entity)
+ public async Task Add(TEntity entity)
{
return await BaseDal.Add(entity);
}
@@ -66,7 +66,7 @@ public async Task Add(TEntity entity)
///
/// 实体集合
/// 影响行数
- public async Task Add(List listEntity)
+ public async Task> Add(List listEntity)
{
return await BaseDal.Add(listEntity);
}
@@ -332,11 +332,14 @@ public async Task> QueryPage(PaginationModel pagination)
var express = DynamicLinqFactory.CreateLambda(pagination.Conditions);
return await QueryPage(express, pagination.PageIndex, pagination.PageSize, pagination.OrderByFileds);
}
+
#region 分表
+
public async Task> AddSplit(TEntity entity)
{
return await BaseDal.AddSplit(entity);
}
+
public async Task UpdateSplit(TEntity entity, DateTime dateTime)
{
return await BaseDal.UpdateSplit(entity, dateTime);
@@ -356,12 +359,14 @@ public async Task QueryByIdSplit(object objId)
{
return await BaseDal.QueryByIdSplit(objId);
}
- public async Task> QueryPageSplit(Expression> whereExpression, DateTime beginTime, DateTime endTime,
+
+ public async Task> QueryPageSplit(Expression> whereExpression, DateTime beginTime, DateTime endTime,
int pageIndex = 1, int pageSize = 20, string orderByFields = null)
{
return await BaseDal.QueryPageSplit(whereExpression, beginTime, endTime,
pageIndex, pageSize, orderByFields);
}
+
#endregion
}
}
\ No newline at end of file
From 0d2a95e0e94553140f550fc4606ef88c8efab824 Mon Sep 17 00:00:00 2001
From: LemonNoCry <773596523@qq.com>
Date: Sat, 1 Apr 2023 23:25:56 +0800
Subject: [PATCH 12/84] =?UTF-8?q?=E2=9C=A8=20=E5=88=9D=E6=AD=A5=E8=B0=83?=
=?UTF-8?q?=E6=95=B4Serilog?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.gitignore | 2 +
Blog.Core.Api/Blog.Core.Api.csproj | 6 +-
Blog.Core.Api/Blog.Core.xml | 2 +-
Blog.Core.Api/Controllers/ValuesController.cs | 2 +-
Blog.Core.Api/Filter/GlobalExceptionFilter.cs | 6 +-
Blog.Core.Api/Log4net.config | 364 -----------
Blog.Core.Api/Program.cs | 112 ++--
Blog.Core.Api/Startup.cs | 1 -
Blog.Core.Api/appsettings.json | 601 +++++++++---------
Blog.Core.Api/skyapm.json | 2 +-
Blog.Core.Common/App.cs | 63 +-
Blog.Core.Common/Blog.Core.Common.csproj | 14 +-
Blog.Core.Common/Const/SqlSugarConst.cs | 9 +
Blog.Core.Common/Core/InternalApp.cs | 25 +-
Blog.Core.Common/DB/Aop/SqlsugarAop.cs | 30 +-
Blog.Core.Common/DB/BaseDBConfig.cs | 3 +-
Blog.Core.Common/Helper/RecursionHelper.cs | 67 +-
.../{ => Https}/HttpPolly/HttpPollyHelper.cs | 20 +-
.../{ => Https}/HttpPolly/IHttpPollyHelper.cs | 2 +-
Blog.Core.Common/Https/RequestIpUtility.cs | 83 +++
Blog.Core.Common/Hubs/ChatHub.cs | 3 +-
.../LogHelper/LogContextExtension.cs | 42 ++
.../LogHelper/LogContextStatic.cs | 42 ++
Blog.Core.Common/LogHelper/LogLock.cs | 170 ++---
.../Blog.Core.Extensions.csproj | 3 +-
.../Middlewares/ExceptionHandlerMiddleware.cs | 9 +-
.../Middlewares/IpLimitMiddleware.cs | 7 +-
.../Middlewares/IpLogMiddleware.cs | 7 +-
.../Middlewares/MiniProfilerMiddleware.cs | 7 +-
.../Middlewares/SignalRSendMiddleware.cs | 1 +
.../Middlewares/SwaggerMiddleware.cs | 21 +-
.../ServiceExtensions/AppConfigSetup.cs | 38 +-
.../AutofacModuleRegister.cs | 20 +-
.../ServiceExtensions/HttpPollySetup.cs | 2 +-
.../ServiceExtensions/SerilogSetup.cs | 37 ++
.../ServiceExtensions/SqlsugarSetup.cs | 45 +-
.../ServiceExtensions/SwaggerSetup.cs | 26 +-
.../Blog.Core.Serilog.Es.csproj | 2 +-
Blog.Core.Serilog/Blog.Core.Serilog.csproj | 13 +
.../LoggerConfigurationExtensions.cs | 121 ++++
.../Utility/SerilogRequestUtility.cs | 34 +
.../Jobs/Job_AccessTrendLog_Quartz.cs | 4 +-
.../QuartzNet/Jobs/Job_OperateLog_Quartz.cs | 17 +-
.../DependencyInjection/DI_Test.cs | 1 -
Blog.Core.sln | 6 +
45 files changed, 1137 insertions(+), 955 deletions(-)
delete mode 100644 Blog.Core.Api/Log4net.config
create mode 100644 Blog.Core.Common/Const/SqlSugarConst.cs
rename Blog.Core.Common/{ => Https}/HttpPolly/HttpPollyHelper.cs (98%)
rename Blog.Core.Common/{ => Https}/HttpPolly/IHttpPollyHelper.cs (96%)
create mode 100644 Blog.Core.Common/Https/RequestIpUtility.cs
create mode 100644 Blog.Core.Common/LogHelper/LogContextExtension.cs
create mode 100644 Blog.Core.Common/LogHelper/LogContextStatic.cs
create mode 100644 Blog.Core.Extensions/ServiceExtensions/SerilogSetup.cs
create mode 100644 Blog.Core.Serilog/Blog.Core.Serilog.csproj
create mode 100644 Blog.Core.Serilog/Extensions/LoggerConfigurationExtensions.cs
create mode 100644 Blog.Core.Serilog/Utility/SerilogRequestUtility.cs
diff --git a/.gitignore b/.gitignore
index b7645c45..4f554bea 100644
--- a/.gitignore
+++ b/.gitignore
@@ -356,3 +356,5 @@ Blog.Core/Blog.Core*.xml
Blog.Core.Api/WMBlog.db
Blog.Core.Api/wwwroot/ui/
*.db
+/Blog.Core.Api/WMBlog.db-journal
+Logs
diff --git a/Blog.Core.Api/Blog.Core.Api.csproj b/Blog.Core.Api/Blog.Core.Api.csproj
index 77d681f1..3bf64399 100644
--- a/Blog.Core.Api/Blog.Core.Api.csproj
+++ b/Blog.Core.Api/Blog.Core.Api.csproj
@@ -26,21 +26,25 @@
+
+
+
+
@@ -51,8 +55,6 @@
-
-
diff --git a/Blog.Core.Api/Blog.Core.xml b/Blog.Core.Api/Blog.Core.xml
index 89cb3213..488903a0 100644
--- a/Blog.Core.Api/Blog.Core.xml
+++ b/Blog.Core.Api/Blog.Core.xml
@@ -760,7 +760,7 @@
Values控制器
-
+
ValuesController
diff --git a/Blog.Core.Api/Controllers/ValuesController.cs b/Blog.Core.Api/Controllers/ValuesController.cs
index 1347ca16..677eb138 100644
--- a/Blog.Core.Api/Controllers/ValuesController.cs
+++ b/Blog.Core.Api/Controllers/ValuesController.cs
@@ -1,7 +1,7 @@
using AutoMapper;
using Blog.Core.Common;
using Blog.Core.Common.HttpContextUser;
-using Blog.Core.Common.HttpPolly;
+using Blog.Core.Common.Https.HttpPolly;
using Blog.Core.Common.WebApiClients.HttpApis;
using Blog.Core.EventBus;
using Blog.Core.EventBus.EventHandling;
diff --git a/Blog.Core.Api/Filter/GlobalExceptionFilter.cs b/Blog.Core.Api/Filter/GlobalExceptionFilter.cs
index da119a6e..44c6124c 100644
--- a/Blog.Core.Api/Filter/GlobalExceptionFilter.cs
+++ b/Blog.Core.Api/Filter/GlobalExceptionFilter.cs
@@ -3,14 +3,10 @@
using Blog.Core.Common.LogHelper;
using Blog.Core.Hubs;
using Blog.Core.Model;
-using Microsoft.AspNetCore.Hosting;
-using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.SignalR;
-using Microsoft.Extensions.Logging;
using StackExchange.Profiling;
-using System;
namespace Blog.Core.Filter
{
@@ -54,7 +50,7 @@ public void OnException(ExceptionContext context)
MiniProfiler.Current.CustomTiming("Errors:", json.msg);
- //采用log4net 进行错误日志记录
+ //进行错误日志记录
_loggerHelper.LogError(json.msg + WriteLog(json.msg, context.Exception));
if (AppSettings.app(new string[] { "Middleware", "SignalRSendLog", "Enabled" }).ObjToBool())
{
diff --git a/Blog.Core.Api/Log4net.config b/Blog.Core.Api/Log4net.config
deleted file mode 100644
index 61bd3739..00000000
--- a/Blog.Core.Api/Log4net.config
+++ /dev/null
@@ -1,364 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/Blog.Core.Api/Program.cs b/Blog.Core.Api/Program.cs
index f5223beb..f7790a8c 100644
--- a/Blog.Core.Api/Program.cs
+++ b/Blog.Core.Api/Program.cs
@@ -1,20 +1,16 @@
// 以下为asp.net 6.0的写法,如果用5.0,请看Program.five.cs文件
-using System.IdentityModel.Tokens.Jwt;
-using System.Reflection;
-using System.Text;
+
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Blog.Core;
using Blog.Core.Common;
using Blog.Core.Common.Core;
-using Blog.Core.Common.LogHelper;
using Blog.Core.Extensions;
using Blog.Core.Extensions.Apollo;
using Blog.Core.Extensions.Middlewares;
+using Blog.Core.Extensions.ServiceExtensions;
using Blog.Core.Filter;
using Blog.Core.Hubs;
-using Blog.Core.IServices;
-using Blog.Core.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Server.Kestrel.Core;
@@ -22,34 +18,38 @@
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
+using Serilog;
+using System.IdentityModel.Tokens.Jwt;
+using System.Reflection;
+using System.Text;
+using Blog.Core.Common.Https;
+using Blog.Core.Serilog.Utility;
var builder = WebApplication.CreateBuilder(args);
+
+
// 1、配置host与容器
builder.Host
-.UseServiceProviderFactory(new AutofacServiceProviderFactory())
-.ConfigureContainer(builder =>
-{
- builder.RegisterModule(new AutofacModuleRegister());
- builder.RegisterModule();
-})
-.ConfigureLogging((hostingContext, builder) =>
-{
- builder.AddFilter("System", LogLevel.Error);
- builder.AddFilter("Microsoft", LogLevel.Error);
- builder.SetMinimumLevel(LogLevel.Error);
- builder.AddLog4Net(Path.Combine(Directory.GetCurrentDirectory(), "Log4net.config"));
-})
-.ConfigureAppConfiguration((hostingContext, config) =>
-{
- config.Sources.Clear();
- config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: false);
- config.AddConfigurationApollo("appsettings.apollo.json");
-});
+ .UseServiceProviderFactory(new AutofacServiceProviderFactory())
+ .ConfigureContainer(builder =>
+ {
+ builder.RegisterModule(new AutofacModuleRegister());
+ builder.RegisterModule();
+ })
+ .ConfigureAppConfiguration((hostingContext, config) =>
+ {
+ config.Sources.Clear();
+ config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: false);
+ config.AddConfigurationApollo("appsettings.apollo.json");
+ });
+builder.ConfigureApplication();
// 2、配置服务
builder.Services.AddSingleton(new AppSettings(builder.Configuration));
-builder.Services.AddSingleton(new LogLock(builder.Environment.ContentRootPath));
+
+
+
builder.Services.AddUiFilesZipSetup(builder.Environment);
Permissions.IsUseIds4 = AppSettings.app(new string[] { "Startup", "IdentityServer4", "Enabled" }).ObjToBool();
@@ -62,6 +62,9 @@
builder.Services.AddRedisCacheSetup();
builder.Services.AddSqlsugarSetup();
builder.Services.AddDbSetup();
+
+builder.Host.AddSerilogSetup();
+
builder.Services.AddAutoMapperSetup();
builder.Services.AddCorsSetup();
builder.Services.AddMiniProfilerSetup();
@@ -92,34 +95,34 @@
builder.Services.AddSignalR().AddNewtonsoftJsonProtocol();
builder.Services.AddScoped();
builder.Services.Configure(x => x.AllowSynchronousIO = true)
- .Configure(x => x.AllowSynchronousIO = true);
+ .Configure(x => x.AllowSynchronousIO = true);
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession();
builder.Services.AddHttpPollySetup();
builder.Services.AddControllers(o =>
-{
- o.Filters.Add(typeof(GlobalExceptionsFilter));
- //o.Conventions.Insert(0, new GlobalRouteAuthorizeConvention());
- o.Conventions.Insert(0, new GlobalRoutePrefixFilter(new RouteAttribute(RoutePrefix.Name)));
-})
-.AddNewtonsoftJson(options =>
-{
- options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
- options.SerializerSettings.ContractResolver = new DefaultContractResolver();
- options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
- //options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
- options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local;
- options.SerializerSettings.Converters.Add(new StringEnumConverter());
-})
-//.AddFluentValidation(config =>
-//{
-// //程序集方式添加验证
-// config.RegisterValidatorsFromAssemblyContaining(typeof(UserRegisterVoValidator));
-// //是否与MvcValidation共存
-// config.DisableDataAnnotationsValidation = true;
-//})
-;
+ {
+ o.Filters.Add(typeof(GlobalExceptionsFilter));
+ //o.Conventions.Insert(0, new GlobalRouteAuthorizeConvention());
+ o.Conventions.Insert(0, new GlobalRoutePrefixFilter(new RouteAttribute(RoutePrefix.Name)));
+ })
+ .AddNewtonsoftJson(options =>
+ {
+ options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
+ options.SerializerSettings.ContractResolver = new DefaultContractResolver();
+ options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
+ //options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
+ options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local;
+ options.SerializerSettings.Converters.Add(new StringEnumConverter());
+ })
+ //.AddFluentValidation(config =>
+ //{
+ // //程序集方式添加验证
+ // config.RegisterValidatorsFromAssemblyContaining(typeof(UserRegisterVoValidator));
+ // //是否与MvcValidation共存
+ // config.DisableDataAnnotationsValidation = true;
+ //})
+ ;
builder.Services.AddEndpointsApiExplorer();
@@ -159,12 +162,23 @@
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseStatusCodePages();
+app.UseSerilogRequestLogging(options =>
+{
+ options.GetLevel = SerilogRequestUtility.GetRequestLevel;
+ options.EnrichDiagnosticContext = (diagnosticContext, httpContext) =>
+ {
+ diagnosticContext.Set("RequestHost", httpContext.Request.Host.Value);
+ diagnosticContext.Set("RequestScheme", httpContext.Request.Scheme);
+ diagnosticContext.Set("RequestIp", httpContext.GetRequestIp());
+ };
+});
app.UseRouting();
if (builder.Configuration.GetValue("AppSettings:UseLoadTest"))
{
app.UseMiddleware();
}
+
app.UseAuthentication();
app.UseAuthorization();
app.UseMiniProfilerMiddleware();
diff --git a/Blog.Core.Api/Startup.cs b/Blog.Core.Api/Startup.cs
index bc1630f1..1364d6a0 100644
--- a/Blog.Core.Api/Startup.cs
+++ b/Blog.Core.Api/Startup.cs
@@ -39,7 +39,6 @@ public void ConfigureServices(IServiceCollection services)
{
// 以下code可能与文章中不一样,对代码做了封装,具体查看右侧 Extensions 文件夹.
services.AddSingleton(new AppSettings(Configuration));
- services.AddSingleton(new LogLock(Env.ContentRootPath));
services.AddUiFilesZipSetup(Env);
Permissions.IsUseIds4 = AppSettings.app(new string[] { "Startup", "IdentityServer4", "Enabled" }).ObjToBool();
diff --git a/Blog.Core.Api/appsettings.json b/Blog.Core.Api/appsettings.json
index 3c117375..c712054c 100644
--- a/Blog.Core.Api/appsettings.json
+++ b/Blog.Core.Api/appsettings.json
@@ -1,98 +1,92 @@
{
- "urls": "http://*:9291", //web服务端口,如果用IIS部署,把这个去掉
- "Logging": {
- "LogLevel": {
- "Default": "Information", //加入Default否则log4net本地写入不了日志
- "Blog.Core.AuthHelper.ApiResponseHandler": "Error"
- },
- "Debug": {
- "IncludeScopes": false,
- "LogLevel": {
- "Default": "Warning"
- }
- },
- "Console": {
- "IncludeScopes": false,
- "LogLevel": {
- "Default": "Warning",
- "Microsoft.Hosting.Lifetime": "Debug"
- }
- },
- "Log4Net": {
- "Name": "Blog.Core"
- }
- },
- "AllowedHosts": "*",
- "Redis": {
- "ConnectionString": "127.0.0.1:6319,password=admin"
+ "urls": "http://*:9291", //web服务端口,如果用IIS部署,把这个去掉
+ "Serilog": {
+ "MinimumLevel": {
+ "Default": "Debug",
+ "Override": {
+ "Microsoft": "Information",
+ "Microsoft.AspNetCore": "Warning",
+ "System": "Warning",
+ "System.Net.Http.HttpClient": "Warning",
+ "Hangfire": "Information",
+ "Magicodes": "Warning",
+ "DotNetCore.CAP": "Information",
+ "Savorboard.CAP": "Information",
+ "Quartz": "Information"
+ }
+ }
+ },
+ "AllowedHosts": "*",
+ "Redis": {
+ "ConnectionString": "127.0.0.1:6319,password=admin"
+ },
+ "RabbitMQ": {
+ "Enabled": false,
+ "Connection": "118.25.251.13",
+ "UserName": "",
+ "Password": "!",
+ "RetryCount": 3
+ },
+ "Kafka": {
+ "Enabled": false,
+ "Servers": "localhost:9092",
+ "Topic": "blog",
+ "GroupId": "blog-consumer",
+ "NumPartitions": 3 //主题分区数量
+ },
+ "EventBus": {
+ "Enabled": false,
+ "SubscriptionClientName": "Blog.Core"
+ },
+ "AppSettings": {
+ "RedisCachingAOP": {
+ "Enabled": false
},
- "RabbitMQ": {
- "Enabled": false,
- "Connection": "118.25.251.13",
- "UserName": "",
- "Password": "!",
- "RetryCount": 3
+ "MemoryCachingAOP": {
+ "Enabled": true
},
- "Kafka": {
- "Enabled": false,
- "Servers": "localhost:9092",
- "Topic": "blog",
- "GroupId": "blog-consumer",
- "NumPartitions": 3 //主题分区数量
+ "LogAOP": {
+ "Enabled": true,
+ "LogToFile": {
+ "Enabled": false
+ },
+ "LogToDB": {
+ "Enabled": true
+ }
},
- "EventBus": {
- "Enabled": false,
- "SubscriptionClientName": "Blog.Core"
+ "TranAOP": {
+ "Enabled": true
},
- "AppSettings": {
- "RedisCachingAOP": {
- "Enabled": false
- },
- "MemoryCachingAOP": {
- "Enabled": true
- },
- "LogAOP": {
- "Enabled": true,
- "LogToFile": {
- "Enabled": false
- },
- "LogToDB": {
- "Enabled": true
- }
- },
- "TranAOP": {
- "Enabled": true
- },
- "SqlAOP": {
- "Enabled": true,
- "LogToFile": {
- "Enabled": false
- },
- "LogToDB": {
- "Enabled": false
- },
- "LogToConsole": {
- "Enabled": true
- }
- },
- "Date": "2018-08-28",
- "SeedDBEnabled": true, //只生成表结构
- "SeedDBDataEnabled": true, //生成表,并初始化数据
- "Author": "Blog.Core",
- "SvcName": "", // /svc/blog
- "UseLoadTest": false
+ "SqlAOP": {
+ "Enabled": true,
+ "LogToFile": {
+ "Enabled": true
+ },
+ "LogToDB": {
+ "Enabled": false
+ },
+ "LogToConsole": {
+ "Enabled": true
+ }
},
+ "Date": "2018-08-28",
+ "SeedDBEnabled": true, //只生成表结构
+ "SeedDBDataEnabled": true, //生成表,并初始化数据
+ "Author": "Blog.Core",
+ "SvcName": "", // /svc/blog
+ "UseLoadTest": false
+ },
- // 请配置MainDB为你想要的主库的ConnId值,并设置对应的Enabled为true;
- // *** 单库操作,把 MutiDBEnabled 设为false ***;
- // *** 多库操作,把 MutiDBEnabled 设为true,其他的从库Enabled也为true **;
- // 具体配置看视频:https://www.bilibili.com/video/BV1BJ411B7mn?p=6
-
- "MainDB": "WMBLOG_SQLITE", //当前项目的主库,所对应的连接字符串的Enabled必须为true
- "MutiDBEnabled": false, //是否开启多库模式
- "CQRSEnabled": false, //是否开启读写分离模式,必须是单库模式,且数据库类型一致,比如都是SqlServer
- "DBS": [
- /*
+ // 请配置MainDB为你想要的主库的ConnId值,并设置对应的Enabled为true;
+ // *** 单库操作,把 MutiDBEnabled 设为false ***;
+ // *** 多库操作,把 MutiDBEnabled 设为true,其他的从库Enabled也为true **;
+ // 具体配置看视频:https://www.bilibili.com/video/BV1BJ411B7mn?p=6
+ //Log:日志库;
+ "MainDB": "WMBLOG_SQLITE", //当前项目的主库,所对应的连接字符串的Enabled必须为true
+ "MutiDBEnabled": true, //是否开启多库模式
+ "CQRSEnabled": false, //是否开启读写分离模式,必须是单库模式,且数据库类型一致,比如都是SqlServer
+ "DBS": [
+ /*
对应下边的 DBType
MySql = 0,
SqlServer = 1,
@@ -102,225 +96,232 @@
Dm = 5,//达梦
Kdbndp = 6,//人大金仓
*/
- {
- "ConnId": "WMBLOG_SQLITE",
- "DBType": 2,
- "Enabled": true,
- "HitRate": 50, // 值越大,优先级越高
- "Connection": "WMBlog.db" //sqlite只写数据库名就行
- },
- {
- "ConnId": "WMBLOG_MSSQL_1",
- "DBType": 1,
- "Enabled": false,
- "HitRate": 40,
- "Connection": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=WMBLOG_MSSQL_1;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False",
- "ProviderName": "System.Data.SqlClient"
- },
- {
- "ConnId": "WMBLOG_MSSQL_2",
- "DBType": 1,
- "Enabled": false,
- "HitRate": 30,
- "Connection": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=WMBLOG_MSSQL_2;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False",
- "ProviderName": "System.Data.SqlClient"
- },
- {
- "ConnId": "WMBLOG_MYSQL",
- "DBType": 0,
- "Enabled": false,
- "HitRate": 20,
- "Connection": "server=localhost;Database=blog;Uid=root;Pwd=root;Port=3306;Allow User Variables=True;"
- },
- {
- "ConnId": "WMBLOG_MYSQL_2",
- "DBType": 0,
- "Enabled": false,
- "HitRate": 20,
- "Connection": "server=localhost;Database=blogcore001;Uid=root;Pwd=root;Port=3306;Allow User Variables=True;"
- },
- {
- "ConnId": "WMBLOG_ORACLE",
- "DBType": 3,
- "Enabled": false,
- "HitRate": 10,
- "Connection": "Data Source=127.0.0.1/ops;User ID=OPS;Password=123456;Persist Security Info=True;Connection Timeout=60;"
- },
- {
- "ConnId": "WMBLOG_DM",
- "DBType": 5,
- "Enabled": false,
- "HitRate": 10,
- "Connection": "PORT=5236;DATABASE=DAMENG;HOST=localhost;PASSWORD=SYSDBA;USER ID=SYSDBA;"
- },
- {
- "ConnId": "WMBLOG_KDBNDP",
- "DBType": 6,
- "Enabled": false,
- "HitRate": 10,
- "Connection": "Server=127.0.0.1;Port=54321;UID=SYSTEM;PWD=system;database=SQLSUGAR4XTEST1;"
- }
- ],
- "Audience": {
- "Secret": "sdfsdfsrty45634kkhllghtdgdfss345t678fs", //不要太短,16位+
- "SecretFile": "C:\\my-file\\blog.core.audience.secret.txt", //安全。内容就是Secret
- "Issuer": "Blog.Core",
- "Audience": "wr"
+ {
+ "ConnId": "WMBLOG_SQLITE",
+ "DBType": 2,
+ "Enabled": true,
+ "HitRate": 50, // 值越大,优先级越高
+ "Connection": "WMBlog.db" //sqlite只写数据库名就行
},
- "Mongo": {
- "ConnectionString": "mongodb://nosql.data",
- "Database": "BlogCoreDb"
+ {
+ "ConnId": "Log",
+ "DBType": 2,
+ "Enabled": true,
+ "HitRate": 50, // 值越大,优先级越高
+ "Connection": "WMBlogLog.db" //sqlite只写数据库名就行
},
- "Startup": {
- "Domain": "http://localhost:9291",
- "Cors": {
- "PolicyName": "CorsIpAccess", //策略名称
- "EnableAllIPs": false, //当为true时,开放所有IP均可访问。
- // 支持多个域名端口,注意端口号后不要带/斜杆:比如localhost:8000/,是错的
- // 注意,http://127.0.0.1:1818 和 http://localhost:1818 是不一样的
- "IPs": "http://127.0.0.1:2364,http://localhost:2364,http://127.0.0.1:6688,http://localhost:6688"
- },
- "AppConfigAlert": {
- "Enabled": true
- },
- "ApiName": "Blog.Core",
- "IdentityServer4": {
- "Enabled": false, // 这里默认是false,表示使用jwt,如果设置为true,则表示系统使用Ids4模式
- "AuthorizationUrl": "http://localhost:5004", // 认证中心域名
- "ApiName": "blog.core.api" // 资源服务器
- },
- "Authing": {
- "Enabled": false,
- "Issuer": "https://uldr24esx31h-demo.authing.cn/oidc",
- "Audience": "63d51c4205c2849803be5178",
- "JwksUri": "https://uldr24esx31h-demo.authing.cn/oidc/.well-known/jwks.json"
- },
- "RedisMq": {
- "Enabled": false //redis 消息队列
- },
- "MiniProfiler": {
- "Enabled": false //性能分析开启
- },
- "Nacos": {
- "Enabled": false //Nacos注册中心
- }
+ {
+ "ConnId": "WMBLOG_MSSQL_1",
+ "DBType": 1,
+ "Enabled": false,
+ "HitRate": 40,
+ "Connection": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=WMBLOG_MSSQL_1;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False",
+ "ProviderName": "System.Data.SqlClient"
},
- "Middleware": {
- "RequestResponseLog": {
- "Enabled": true,
- "LogToFile": {
- "Enabled": false
- },
- "LogToDB": {
- "Enabled": true
- }
- },
- "IPLog": {
- "Enabled": true,
- "LogToFile": {
- "Enabled": false
- },
- "LogToDB": {
- "Enabled": true
- }
- },
- "RecordAccessLogs": {
- "Enabled": true,
- "LogToFile": {
- "Enabled": false
- },
- "LogToDB": {
- "Enabled": true
- },
- "IgnoreApis": "/api/permission/getnavigationbar,/api/monitor/getids4users,/api/monitor/getaccesslogs,/api/monitor/server,/api/monitor/getactiveusers,/api/monitor/server,"
- },
- "SignalR": {
- "Enabled": false
- },
- "SignalRSendLog": {
- "Enabled": false
- },
- "QuartzNetJob": {
- "Enabled": true
- },
- "Consul": {
- "Enabled": false
- },
- "IpRateLimit": {
- "Enabled": true
- }
+ {
+ "ConnId": "WMBLOG_MSSQL_2",
+ "DBType": 1,
+ "Enabled": false,
+ "HitRate": 30,
+ "Connection": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=WMBLOG_MSSQL_2;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False",
+ "ProviderName": "System.Data.SqlClient"
},
- "IpRateLimiting": {
- "EnableEndpointRateLimiting": true, //False: globally executed, true: executed for each
- "StackBlockedRequests": false, //False: Number of rejections should be recorded on another counter
- "RealIpHeader": "X-Real-IP",
- "ClientIdHeader": "X-ClientId",
- "IpWhitelist": [], //白名单
- "EndpointWhitelist": [ "get:/api/xxx", "*:/api/yyy" ],
- "ClientWhitelist": [ "dev-client-1", "dev-client-2" ],
- "QuotaExceededResponse": {
- "Content": "{{\"status\":429,\"msg\":\"访问过于频繁,请稍后重试\",\"success\":false}}",
- "ContentType": "application/json",
- "StatusCode": 429
- },
- "HttpStatusCode": 429, //返回状态码
- "GeneralRules": [ //api规则,结尾一定要带*
- {
- "Endpoint": "*:/api/blog*",
- "Period": "1m",
- "Limit": 20
- },
- {
- "Endpoint": "*/api/*",
- "Period": "1s",
- "Limit": 3
- },
- {
- "Endpoint": "*/api/*",
- "Period": "1m",
- "Limit": 30
- },
- {
- "Endpoint": "*/api/*",
- "Period": "12h",
- "Limit": 500
- }
- ]
-
+ {
+ "ConnId": "WMBLOG_MYSQL",
+ "DBType": 0,
+ "Enabled": false,
+ "HitRate": 20,
+ "Connection": "server=localhost;Database=blog;Uid=root;Pwd=root;Port=3306;Allow User Variables=True;"
+ },
+ {
+ "ConnId": "WMBLOG_MYSQL_2",
+ "DBType": 0,
+ "Enabled": false,
+ "HitRate": 20,
+ "Connection": "server=localhost;Database=blogcore001;Uid=root;Pwd=root;Port=3306;Allow User Variables=True;"
+ },
+ {
+ "ConnId": "WMBLOG_ORACLE",
+ "DBType": 3,
+ "Enabled": false,
+ "HitRate": 10,
+ "Connection": "Data Source=127.0.0.1/ops;User ID=OPS;Password=123456;Persist Security Info=True;Connection Timeout=60;"
+ },
+ {
+ "ConnId": "WMBLOG_DM",
+ "DBType": 5,
+ "Enabled": false,
+ "HitRate": 10,
+ "Connection": "PORT=5236;DATABASE=DAMENG;HOST=localhost;PASSWORD=SYSDBA;USER ID=SYSDBA;"
+ },
+ {
+ "ConnId": "WMBLOG_KDBNDP",
+ "DBType": 6,
+ "Enabled": false,
+ "HitRate": 10,
+ "Connection": "Server=127.0.0.1;Port=54321;UID=SYSTEM;PWD=system;database=SQLSUGAR4XTEST1;"
+ }
+ ],
+ "Audience": {
+ "Secret": "sdfsdfsrty45634kkhllghtdgdfss345t678fs", //不要太短,16位+
+ "SecretFile": "C:\\my-file\\blog.core.audience.secret.txt", //安全。内容就是Secret
+ "Issuer": "Blog.Core",
+ "Audience": "wr"
+ },
+ "Mongo": {
+ "ConnectionString": "mongodb://nosql.data",
+ "Database": "BlogCoreDb"
+ },
+ "Startup": {
+ "Domain": "http://localhost:9291",
+ "Cors": {
+ "PolicyName": "CorsIpAccess", //策略名称
+ "EnableAllIPs": false, //当为true时,开放所有IP均可访问。
+ // 支持多个域名端口,注意端口号后不要带/斜杆:比如localhost:8000/,是错的
+ // 注意,http://127.0.0.1:1818 和 http://localhost:1818 是不一样的
+ "IPs": "http://127.0.0.1:2364,http://localhost:2364,http://127.0.0.1:6688,http://localhost:6688"
+ },
+ "AppConfigAlert": {
+ "Enabled": true
+ },
+ "ApiName": "Blog.Core",
+ "IdentityServer4": {
+ "Enabled": false, // 这里默认是false,表示使用jwt,如果设置为true,则表示系统使用Ids4模式
+ "AuthorizationUrl": "http://localhost:5004", // 认证中心域名
+ "ApiName": "blog.core.api" // 资源服务器
},
- "ConsulSetting": {
- "ServiceName": "BlogCoreService",
- "ServiceIP": "localhost",
- "ServicePort": "9291",
- "ServiceHealthCheck": "/healthcheck",
- "ConsulAddress": "http://localhost:8500"
+ "Authing": {
+ "Enabled": false,
+ "Issuer": "https://uldr24esx31h-demo.authing.cn/oidc",
+ "Audience": "63d51c4205c2849803be5178",
+ "JwksUri": "https://uldr24esx31h-demo.authing.cn/oidc/.well-known/jwks.json"
},
- "PayInfo": { //建行聚合支付信息
- "MERCHANTID": "", //商户号
- "POSID": "", //柜台号
- "BRANCHID": "", //分行号
- "pubKey": "", //公钥
- "USER_ID": "", //操作员号
- "PASSWORD": "", //密码
- "OutAddress": "http://127.0.0.1:12345" //外联地址
+ "RedisMq": {
+ "Enabled": false //redis 消息队列
},
- "nacos": {
- "ServerAddresses": [ "http://localhost:8848" ], // nacos 连接地址
- "DefaultTimeOut": 15000, // 默认超时时间
- "Namespace": "public", // 命名空间
- "ListenInterval": 10000, // 监听的频率
- "ServiceName": "blog.Core.Api", // 服务名
- "Port": "9291", // 服务端口号
- "RegisterEnabled": true // 是否直接注册nacos
+ "MiniProfiler": {
+ "Enabled": false //性能分析开启
},
- "LogFiedOutPutConfigs": {
- "tcpAddressHost": "", // 输出elk的tcp连接地址
- "tcpAddressPort": 0, // 输出elk的tcp端口号
- "ConfigsInfo": [ // 配置的输出elk节点内容 常用语动态标识
- {
- "FiedName": "applicationName",
- "FiedValue": "Blog.Core.Api"
- }
- ]
+ "Nacos": {
+ "Enabled": false //Nacos注册中心
}
+ },
+ "Middleware": {
+ "RequestResponseLog": {
+ "Enabled": true,
+ "LogToFile": {
+ "Enabled": false
+ },
+ "LogToDB": {
+ "Enabled": true
+ }
+ },
+ "IPLog": {
+ "Enabled": true,
+ "LogToFile": {
+ "Enabled": false
+ },
+ "LogToDB": {
+ "Enabled": true
+ }
+ },
+ "RecordAccessLogs": {
+ "Enabled": true,
+ "LogToFile": {
+ "Enabled": false
+ },
+ "LogToDB": {
+ "Enabled": true
+ },
+ "IgnoreApis": "/api/permission/getnavigationbar,/api/monitor/getids4users,/api/monitor/getaccesslogs,/api/monitor/server,/api/monitor/getactiveusers,/api/monitor/server,"
+ },
+ "SignalR": {
+ "Enabled": false
+ },
+ "SignalRSendLog": {
+ "Enabled": false
+ },
+ "QuartzNetJob": {
+ "Enabled": true
+ },
+ "Consul": {
+ "Enabled": false
+ },
+ "IpRateLimit": {
+ "Enabled": true
+ }
+ },
+ "IpRateLimiting": {
+ "EnableEndpointRateLimiting": true, //False: globally executed, true: executed for each
+ "StackBlockedRequests": false, //False: Number of rejections should be recorded on another counter
+ "RealIpHeader": "X-Real-IP",
+ "ClientIdHeader": "X-ClientId",
+ "IpWhitelist": [], //白名单
+ "EndpointWhitelist": [ "get:/api/xxx", "*:/api/yyy" ],
+ "ClientWhitelist": [ "dev-client-1", "dev-client-2" ],
+ "QuotaExceededResponse": {
+ "Content": "{{\"status\":429,\"msg\":\"访问过于频繁,请稍后重试\",\"success\":false}}",
+ "ContentType": "application/json",
+ "StatusCode": 429
+ },
+ "HttpStatusCode": 429, //返回状态码
+ "GeneralRules": [ //api规则,结尾一定要带*
+ {
+ "Endpoint": "*:/api/blog*",
+ "Period": "1m",
+ "Limit": 20
+ },
+ {
+ "Endpoint": "*/api/*",
+ "Period": "1s",
+ "Limit": 3
+ },
+ {
+ "Endpoint": "*/api/*",
+ "Period": "1m",
+ "Limit": 30
+ },
+ {
+ "Endpoint": "*/api/*",
+ "Period": "12h",
+ "Limit": 500
+ }
+ ]
+
+ },
+ "ConsulSetting": {
+ "ServiceName": "BlogCoreService",
+ "ServiceIP": "localhost",
+ "ServicePort": "9291",
+ "ServiceHealthCheck": "/healthcheck",
+ "ConsulAddress": "http://localhost:8500"
+ },
+ "PayInfo": { //建行聚合支付信息
+ "MERCHANTID": "", //商户号
+ "POSID": "", //柜台号
+ "BRANCHID": "", //分行号
+ "pubKey": "", //公钥
+ "USER_ID": "", //操作员号
+ "PASSWORD": "", //密码
+ "OutAddress": "http://127.0.0.1:12345" //外联地址
+ },
+ "nacos": {
+ "ServerAddresses": [ "http://localhost:8848" ], // nacos 连接地址
+ "DefaultTimeOut": 15000, // 默认超时时间
+ "Namespace": "public", // 命名空间
+ "ListenInterval": 10000, // 监听的频率
+ "ServiceName": "blog.Core.Api", // 服务名
+ "Port": "9291", // 服务端口号
+ "RegisterEnabled": true // 是否直接注册nacos
+ },
+ "LogFiedOutPutConfigs": {
+ "tcpAddressHost": "", // 输出elk的tcp连接地址
+ "tcpAddressPort": 0, // 输出elk的tcp端口号
+ "ConfigsInfo": [ // 配置的输出elk节点内容 常用语动态标识
+ {
+ "FiedName": "applicationName",
+ "FiedValue": "Blog.Core.Api"
+ }
+ ]
+ }
}
diff --git a/Blog.Core.Api/skyapm.json b/Blog.Core.Api/skyapm.json
index cd5ed0ee..cdb0e606 100644
--- a/Blog.Core.Api/skyapm.json
+++ b/Blog.Core.Api/skyapm.json
@@ -11,7 +11,7 @@
},
"Logging": {
"Level": "Information",
- "FilePath": "Log/skyapm-{Date}.log"
+ "FilePath": "Logs/Skyapm/skyapm-{Date}.log"
},
"Transport": {
"Interval": 3000,
diff --git a/Blog.Core.Common/App.cs b/Blog.Core.Common/App.cs
index 008aea5d..c2e2e706 100644
--- a/Blog.Core.Common/App.cs
+++ b/Blog.Core.Common/App.cs
@@ -1,14 +1,24 @@
using Blog.Core.Common.Core;
using Blog.Core.Common.HttpContextUser;
+using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Hosting;
+using Microsoft.Extensions.Options;
using System;
+using System.Linq;
namespace Blog.Core.Common;
public class App
{
- public static IServiceProvider RootServices => InternalApp.RootServices ;
+ public static IServiceProvider RootServices => InternalApp.RootServices;
+
+ /// 获取Web主机环境,如,是否是开发环境,生产环境等
+ public static IWebHostEnvironment WebHostEnvironment => InternalApp.WebHostEnvironment;
+
+ /// 获取泛型主机环境,如,是否是开发环境,生产环境等
+ public static IHostEnvironment HostEnvironment => InternalApp.HostEnvironment;
///
/// 获取请求上下文
@@ -16,4 +26,55 @@ public class App
public static HttpContext HttpContext => RootServices?.GetService()?.HttpContext;
public static IUser User => HttpContext == null ? null : RootServices?.GetService();
+
+ /// 解析服务提供器
+ ///
+ ///
+ public static IServiceProvider GetServiceProvider(Type serviceType, bool mustBuild = false)
+ {
+ if (App.HostEnvironment == null || App.RootServices != null &&
+ InternalApp.InternalServices
+ .Where((u => u.ServiceType == (serviceType.IsGenericType ? serviceType.GetGenericTypeDefinition() : serviceType)))
+ .Any((u => u.Lifetime == ServiceLifetime.Singleton)))
+ return App.RootServices;
+ HttpContext httpContext = App.HttpContext;
+ if (httpContext?.RequestServices != null)
+ return httpContext.RequestServices;
+ if (App.RootServices != null)
+ {
+ IServiceScope scope = App.RootServices.CreateScope();
+ return scope.ServiceProvider;
+ }
+
+ if (mustBuild)
+ {
+ throw new ApplicationException("当前不可用,必须要等到 WebApplication Build后");
+ }
+
+ ServiceProvider serviceProvider = InternalApp.InternalServices.BuildServiceProvider();
+ return serviceProvider;
+ }
+
+
+ public static TService GetService(bool mustBuild = true) where TService : class => App.GetService(typeof(TService), null, mustBuild) as TService;
+
+ /// 获取请求生存周期的服务
+ ///
+ ///
+ ///
+ ///
+ public static TService GetService(IServiceProvider serviceProvider, bool mustBuild = true) where TService : class => App.GetService(typeof(TService), serviceProvider, mustBuild) as TService;
+
+ /// 获取请求生存周期的服务
+ ///
+ ///
+ ///
+ ///
+ public static object GetService(Type type, IServiceProvider serviceProvider = null, bool mustBuild = true) => (serviceProvider ?? App.GetServiceProvider(type, mustBuild)).GetService(type);
+
+ public static TOptions GetOptions(IServiceProvider serviceProvider = null) where TOptions : class, new()
+ {
+ IOptions service = App.GetService>(serviceProvider ?? App.RootServices, false);
+ return service?.Value;
+ }
}
\ No newline at end of file
diff --git a/Blog.Core.Common/Blog.Core.Common.csproj b/Blog.Core.Common/Blog.Core.Common.csproj
index fc0abb9d..0662bac5 100644
--- a/Blog.Core.Common/Blog.Core.Common.csproj
+++ b/Blog.Core.Common/Blog.Core.Common.csproj
@@ -18,20 +18,23 @@
-
+
-
+
+
+
+
+
-
-
-
+
+
@@ -45,6 +48,7 @@
+
diff --git a/Blog.Core.Common/Const/SqlSugarConst.cs b/Blog.Core.Common/Const/SqlSugarConst.cs
new file mode 100644
index 00000000..f5efd7e2
--- /dev/null
+++ b/Blog.Core.Common/Const/SqlSugarConst.cs
@@ -0,0 +1,9 @@
+namespace Blog.Core.Common.Const;
+
+public class SqlSugarConst
+{
+ ///
+ /// 默认Log数据库标识
+ ///
+ public const string LogConfigId = "Log";
+}
\ No newline at end of file
diff --git a/Blog.Core.Common/Core/InternalApp.cs b/Blog.Core.Common/Core/InternalApp.cs
index c1ae8dcd..62e04724 100644
--- a/Blog.Core.Common/Core/InternalApp.cs
+++ b/Blog.Core.Common/Core/InternalApp.cs
@@ -1,17 +1,34 @@
-using Microsoft.AspNetCore.Builder;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Hosting;
using System;
+using Microsoft.AspNetCore.Builder;
+using Microsoft.AspNetCore.Hosting;
namespace Blog.Core.Common.Core;
public static class InternalApp
{
+ public static IServiceCollection InternalServices;
+
/// 根服务
public static IServiceProvider RootServices;
- public static void ConfigureApplication(this WebApplication app)
+ /// 获取Web主机环境
+ public static IWebHostEnvironment WebHostEnvironment;
+
+ /// 获取泛型主机环境
+ public static IHostEnvironment HostEnvironment;
+
+ public static void ConfigureApplication(this WebApplicationBuilder wab)
{
- app.Lifetime.ApplicationStarted.Register(() => { InternalApp.RootServices = app.Services; });
+ HostEnvironment = wab.Environment;
+ WebHostEnvironment = wab.Environment;
+ InternalServices = wab.Services;
+ }
+
- app.Lifetime.ApplicationStopped.Register(() => { InternalApp.RootServices = null; });
+ public static void ConfigureApplication(this IHost app)
+ {
+ RootServices = app.Services;
}
}
\ No newline at end of file
diff --git a/Blog.Core.Common/DB/Aop/SqlsugarAop.cs b/Blog.Core.Common/DB/Aop/SqlsugarAop.cs
index 3d83b002..c3d374ae 100644
--- a/Blog.Core.Common/DB/Aop/SqlsugarAop.cs
+++ b/Blog.Core.Common/DB/Aop/SqlsugarAop.cs
@@ -1,12 +1,40 @@
-using Blog.Core.Model.Models.RootTkey;
+using Blog.Core.Common.LogHelper;
+using Blog.Core.Model.Models.RootTkey;
using Blog.Core.Model.Tenants;
using SqlSugar;
+using StackExchange.Profiling;
using System;
+using Serilog;
namespace Blog.Core.Common.DB.Aop;
public static class SqlSugarAop
{
+ public static void OnLogExecuting(ISqlSugarClient sqlSugarScopeProvider, string sql, SugarParameter[] p, ConnectionConfig config)
+ {
+ try
+ {
+ MiniProfiler.Current.CustomTiming($"ConnId:[{config.ConfigId}] SQL:", GetParas(p) + "【SQL语句】:" + sql);
+
+ if (!AppSettings.app(new string[] { "AppSettings", "SqlAOP", "Enabled" }).ObjToBool()) return;
+
+ if (AppSettings.app(new string[] { "AppSettings", "SqlAOP", "LogToConsole", "Enabled" }).ObjToBool() ||
+ AppSettings.app(new string[] { "AppSettings", "SqlAOP", "LogToFile", "Enabled" }).ObjToBool() ||
+ AppSettings.app(new string[] { "AppSettings", "SqlAOP", "LogToDB", "Enabled" }).ObjToBool())
+ {
+ using (LogContextExtension.Create.SqlAopPushProperty(sqlSugarScopeProvider))
+ {
+ Log.Information("------------------ \r\n ConnId:[{ConnId}]【SQL语句】: \r\n {Sql}",
+ config.ConfigId, UtilMethods.GetSqlString(config.DbType, sql, p));
+ }
+ }
+ }
+ catch (Exception e)
+ {
+ Log.Error("Error occured OnLogExcuting:" + e);
+ }
+ }
+
public static void DataExecuting(object oldValue, DataFilterModel entityInfo)
{
if (entityInfo.EntityValue is BaseEntity root)
diff --git a/Blog.Core.Common/DB/BaseDBConfig.cs b/Blog.Core.Common/DB/BaseDBConfig.cs
index 1d86369a..d8c3ee50 100644
--- a/Blog.Core.Common/DB/BaseDBConfig.cs
+++ b/Blog.Core.Common/DB/BaseDBConfig.cs
@@ -12,6 +12,7 @@ public class BaseDBConfig
* 目前是多库操作,默认加载的是appsettings.json设置为true的第一个db连接。
*/
public static (List allDbs, List slaveDbs) MutiConnectionString => MutiInitConn();
+ public static ConnectionConfig LogConfig; //日志库
private static string DifDBConnOfSecurity(params string[] conn)
{
@@ -107,8 +108,6 @@ private static MutiDBOperate SpecialDbString(MutiDBOperate mutiDBOperate)
return mutiDBOperate;
}
-
-
}
diff --git a/Blog.Core.Common/Helper/RecursionHelper.cs b/Blog.Core.Common/Helper/RecursionHelper.cs
index 9b27a37d..b4cbd682 100644
--- a/Blog.Core.Common/Helper/RecursionHelper.cs
+++ b/Blog.Core.Common/Helper/RecursionHelper.cs
@@ -1,4 +1,5 @@
-using System.Collections.Generic;
+using System;
+using System.Collections.Generic;
using System.Linq;
namespace Blog.Core.Common.Helper
@@ -8,9 +9,8 @@ namespace Blog.Core.Common.Helper
///
public static class RecursionHelper
{
- public static void LoopToAppendChildren(List all, PermissionTree curItem, int pid, bool needbtn)
+ public static void LoopToAppendChildren(List all, PermissionTree curItem, long pid, bool needbtn)
{
-
var subItems = all.Where(ee => ee.Pid == curItem.value).ToList();
var btnItems = subItems.Where(ss => ss.isbtn == true).ToList();
@@ -28,6 +28,7 @@ public static void LoopToAppendChildren(List all, PermissionTree
{
subItems = subItems.Where(ss => ss.isbtn == false).ToList();
}
+
if (subItems.Count > 0)
{
curItem.children = new List();
@@ -49,14 +50,15 @@ public static void LoopToAppendChildren(List all, PermissionTree
{
//subItem.disabled = true;//禁用当前节点
}
+
LoopToAppendChildren(all, subItem, pid, needbtn);
}
}
+
public static void LoopToAppendChildren(List all, DepartmentTree curItem, int pid)
{
-
var subItems = all.Where(ee => ee.Pid == curItem.value).ToList();
-
+
if (subItems.Count > 0)
{
curItem.children = new List();
@@ -73,15 +75,14 @@ public static void LoopToAppendChildren(List all, DepartmentTree
{
//subItem.disabled = true;//禁用当前节点
}
+
LoopToAppendChildren(all, subItem, pid);
}
}
-
public static void LoopNaviBarAppendChildren(List all, NavigationBar curItem)
{
-
var subItems = all.Where(ee => ee.pid == curItem.id).ToList();
if (subItems.Count > 0)
@@ -102,7 +103,6 @@ public static void LoopNaviBarAppendChildren(List all, Navigation
}
-
public static void LoopToAppendChildrenT(List all, T curItem, string parentIdName = "Pid", string idName = "value", string childrenName = "children")
{
var subItems = all.Where(ee => ee.GetType().GetProperty(parentIdName).GetValue(ee, null).ToString() == curItem.GetType().GetProperty(idName).GetValue(curItem, null).ToString()).ToList();
@@ -113,12 +113,47 @@ public static void LoopToAppendChildrenT(List all, T curItem, string paren
LoopToAppendChildrenT(all, subItem);
}
}
+
+ ///
+ /// 将父子级数据结构转换为普通list
+ ///
+ ///
+ ///
+ public static List TreeToList(List list, Action> action = null)
+ {
+ List results = new List();
+ foreach (var item in list)
+ {
+ results.Add(item);
+ OperationChildData(results, item, action);
+ }
+
+ return results;
+ }
+
+ ///
+ /// 递归子级数据
+ ///
+ /// 树形列表数据
+ /// Item
+ public static void OperationChildData(List allList, T item, Action> action)
+ {
+ dynamic dynItem = item;
+ if (dynItem.Children == null) return;
+ if (dynItem.Children.Count <= 0) return;
+ allList.AddRange(dynItem.Children);
+ foreach (var subItem in dynItem.Children)
+ {
+ action?.Invoke(item, subItem, allList);
+ OperationChildData(allList, subItem, action);
+ }
+ }
}
public class PermissionTree
{
- public int value { get; set; }
- public int Pid { get; set; }
+ public long value { get; set; }
+ public long Pid { get; set; }
public string label { get; set; }
public int order { get; set; }
public bool isbtn { get; set; }
@@ -139,8 +174,8 @@ public class DepartmentTree
public class NavigationBar
{
- public int id { get; set; }
- public int pid { get; set; }
+ public long id { get; set; }
+ public long pid { get; set; }
public int order { get; set; }
public string name { get; set; }
public bool IsHide { get; set; } = false;
@@ -158,15 +193,13 @@ public class NavigationBarMeta
public bool requireAuth { get; set; } = true;
public bool NoTabPage { get; set; } = false;
public bool keepAlive { get; set; } = false;
-
-
}
public class NavigationBarPro
{
- public int id { get; set; }
- public int parentId { get; set; }
+ public long id { get; set; }
+ public long parentId { get; set; }
public int order { get; set; }
public string name { get; set; }
public bool IsHide { get; set; } = false;
@@ -184,4 +217,4 @@ public class NavigationBarMetaPro
public string icon { get; set; }
public bool show { get; set; } = false;
}
-}
+}
\ No newline at end of file
diff --git a/Blog.Core.Common/HttpPolly/HttpPollyHelper.cs b/Blog.Core.Common/Https/HttpPolly/HttpPollyHelper.cs
similarity index 98%
rename from Blog.Core.Common/HttpPolly/HttpPollyHelper.cs
rename to Blog.Core.Common/Https/HttpPolly/HttpPollyHelper.cs
index f1a1e84c..1187d711 100644
--- a/Blog.Core.Common/HttpPolly/HttpPollyHelper.cs
+++ b/Blog.Core.Common/Https/HttpPolly/HttpPollyHelper.cs
@@ -6,7 +6,7 @@
using System.Text;
using System.Threading.Tasks;
-namespace Blog.Core.Common.HttpPolly
+namespace Blog.Core.Common.Https.HttpPolly
{
public class HttpPollyHelper : IHttpPollyHelper
{
@@ -35,7 +35,7 @@ public async Task PostAsync(HttpEnum httpEnum, string url, R request, D
var stringContent = new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, "application/json");
var response = await client.PostAsync(url, stringContent);
-
+
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
string result = await response.Content.ReadAsStringAsync();
@@ -72,7 +72,7 @@ public async Task PostAsync(HttpEnum httpEnum, string url, string request,
var stringContent = new StringContent(request, Encoding.UTF8, "application/json");
var response = await client.PostAsync(url, stringContent);
-
+
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
string result = await response.Content.ReadAsStringAsync();
@@ -110,7 +110,7 @@ public async Task PostAsync(HttpEnum httpEnum, string url, R request,
var stringContent = new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, "application/json");
var response = await client.PostAsync(url, stringContent);
-
+
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
return await response.Content.ReadAsStringAsync();
@@ -146,7 +146,7 @@ public async Task PostAsync(HttpEnum httpEnum, string url, string reques
var stringContent = new StringContent(request, Encoding.UTF8, "application/json");
var response = await client.PostAsync(url, stringContent);
-
+
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
return await response.Content.ReadAsStringAsync();
@@ -182,7 +182,7 @@ public async Task GetAsync(HttpEnum httpEnum, string url, Dictionary GetAsync(HttpEnum httpEnum, string url, Dictionary PutAsync(HttpEnum httpEnum, string url, R request, Di
var stringContent = new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, "application/json");
var response = await client.PutAsync(url, stringContent);
-
+
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
string result = await response.Content.ReadAsStringAsync();
@@ -294,7 +294,7 @@ public async Task PutAsync(HttpEnum httpEnum, string url, string request,
var stringContent = new StringContent(request, Encoding.UTF8, "application/json");
var response = await client.PutAsync(url, stringContent);
-
+
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
string result = await response.Content.ReadAsStringAsync();
@@ -331,7 +331,7 @@ public async Task DeleteAsync(HttpEnum httpEnum, string url, Dictionary(context, "X-Forwarded-For")).FirstOrDefault();
+
+ if (string.IsNullOrWhiteSpace(ip))
+ ip = SplitCsv(GetHeaderValueAs(context, "X-Real-IP")).FirstOrDefault();
+
+ if (string.IsNullOrWhiteSpace(ip) && context.Connection?.RemoteIpAddress != null)
+ ip = context.Connection.RemoteIpAddress.ToString();
+
+ if (string.IsNullOrWhiteSpace(ip))
+ ip = GetHeaderValueAs(context, "REMOTE_ADDR");
+
+ return ip;
+ }
+
+ public static bool IsLocal(this HttpContext context)
+ {
+ return GetRequestIp(context) is "127.0.0.1" or "::1" || context.Request?.IsLocal() == true;
+ }
+
+
+ public static bool IsLocal(this HttpRequest req)
+ {
+ var connection = req.HttpContext.Connection;
+ if (connection.RemoteIpAddress != null)
+ {
+ if (connection.LocalIpAddress != null)
+ {
+ return connection.RemoteIpAddress.Equals(connection.LocalIpAddress);
+ }
+ else
+ {
+ return IPAddress.IsLoopback(connection.RemoteIpAddress);
+ }
+ }
+
+ // for in memory TestServer or when dealing with default connection info
+ if (connection.RemoteIpAddress == null && connection.LocalIpAddress == null)
+ {
+ return true;
+ }
+
+ return false;
+ }
+
+
+ private static T GetHeaderValueAs(HttpContext context, string headerName)
+ {
+ if (context.Request?.Headers?.TryGetValue(headerName, out var values) ?? false)
+ {
+ string rawValues = values.ToString();
+
+ if (!string.IsNullOrWhiteSpace(rawValues))
+ return (T) Convert.ChangeType(values.ToString(), typeof(T));
+ }
+
+ return default;
+ }
+
+ private static List SplitCsv(string csvList)
+ {
+ if (string.IsNullOrWhiteSpace(csvList))
+ return new List();
+
+ return csvList
+ .TrimEnd(',')
+ .Split(',')
+ .AsEnumerable()
+ .Select(s => s.Trim())
+ .ToList();
+ }
+}
\ No newline at end of file
diff --git a/Blog.Core.Common/Hubs/ChatHub.cs b/Blog.Core.Common/Hubs/ChatHub.cs
index ff15c97f..1c58c8a0 100644
--- a/Blog.Core.Common/Hubs/ChatHub.cs
+++ b/Blog.Core.Common/Hubs/ChatHub.cs
@@ -83,7 +83,8 @@ public async Task GetLatestCount(string random)
//2、服务端主动向客户端发送数据,名字千万不能错
if (AppSettings.app(new string[] { "Middleware", "SignalRSendLog", "Enabled" }).ObjToBool())
{
- await Clients.All.ReceiveUpdate(LogLock.GetLogData());
+ //TODO 主动发送错误消息
+ //await Clients.All.ReceiveUpdate(LogLock.GetLogData());
}
diff --git a/Blog.Core.Common/LogHelper/LogContextExtension.cs b/Blog.Core.Common/LogHelper/LogContextExtension.cs
new file mode 100644
index 00000000..bce80cbb
--- /dev/null
+++ b/Blog.Core.Common/LogHelper/LogContextExtension.cs
@@ -0,0 +1,42 @@
+using Serilog.Context;
+using SqlSugar;
+using System;
+using System.Collections.Generic;
+
+namespace Blog.Core.Common.LogHelper;
+
+public class LogContextExtension : IDisposable
+{
+ private readonly Stack _disposableStack = new Stack();
+
+ public static LogContextExtension Create => new();
+
+ public void AddStock(IDisposable disposable)
+ {
+ _disposableStack.Push(disposable);
+ }
+
+ public IDisposable SqlAopPushProperty(ISqlSugarClient db)
+ {
+ AddStock(LogContext.PushProperty(LogContextStatic.LogSource, LogContextStatic.AopSql));
+ AddStock(LogContext.PushProperty(LogContextStatic.SqlOutToConsole,
+ AppSettings.app(new string[] { "AppSettings", "SqlAOP", "LogToConsole", "Enabled" }).ObjToBool()));
+ AddStock(LogContext.PushProperty(LogContextStatic.SqlOutToFile,
+ AppSettings.app(new string[] { "AppSettings", "SqlAOP", "LogToFile", "Enabled" }).ObjToBool()));
+ AddStock(LogContext.PushProperty(LogContextStatic.OutToDb,
+ AppSettings.app(new string[] { "AppSettings", "SqlAOP", "LogToDb", "Enabled" }).ObjToBool()));
+
+ AddStock(LogContext.PushProperty(LogContextStatic.SugarActionType, db.SugarActionType));
+
+ return this;
+ }
+
+
+ public void Dispose()
+ {
+ while (_disposableStack.Count > 0)
+ {
+ _disposableStack.Pop().Dispose();
+ }
+ }
+}
\ No newline at end of file
diff --git a/Blog.Core.Common/LogHelper/LogContextStatic.cs b/Blog.Core.Common/LogHelper/LogContextStatic.cs
new file mode 100644
index 00000000..52a8167d
--- /dev/null
+++ b/Blog.Core.Common/LogHelper/LogContextStatic.cs
@@ -0,0 +1,42 @@
+using System.IO;
+
+namespace Blog.Core.Common.LogHelper;
+
+public class LogContextStatic
+{
+ static LogContextStatic()
+ {
+ if (!Directory.Exists(BaseLogs))
+ {
+ Directory.CreateDirectory(BaseLogs);
+ }
+ }
+
+ public static readonly string BaseLogs = "Logs";
+ public static readonly string BasePathLogs = @"Logs";
+
+ public static readonly string LogSource = "LogSource";
+ public static readonly string AopSql = "AopSql";
+ public static readonly string SqlOutToConsole = "OutToConsole";
+ public static readonly string SqlOutToFile = "SqlOutToFile";
+ public static readonly string OutToDb = "OutToDb";
+ public static readonly string SugarActionType = "SugarActionType";
+
+ public static readonly string FileMessageTemplate = "{NewLine}Date:{Timestamp:yyyy-MM-dd HH:mm:ss.fff}{NewLine}LogLevel:{Level}{NewLine}Message:{Message}{NewLine}{Exception}" + new string('-', 100);
+
+
+ public static string Combine(string path1)
+ {
+ return Path.Combine(BaseLogs, path1);
+ }
+
+ public static string Combine(string path1, string path2)
+ {
+ return Path.Combine(BaseLogs, path1, path2);
+ }
+
+ public static string Combine(string path1, string path2, string path3)
+ {
+ return Path.Combine(BaseLogs, path1, path2, path3);
+ }
+}
\ No newline at end of file
diff --git a/Blog.Core.Common/LogHelper/LogLock.cs b/Blog.Core.Common/LogHelper/LogLock.cs
index 70c5f7f2..2c9be9a9 100644
--- a/Blog.Core.Common/LogHelper/LogLock.cs
+++ b/Blog.Core.Common/LogHelper/LogLock.cs
@@ -1,5 +1,4 @@
using Blog.Core.Common.Helper;
-using log4net;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
@@ -7,12 +6,12 @@
using System.Linq;
using System.Text;
using System.Threading;
+using Serilog;
namespace Blog.Core.Common.LogHelper
{
public class LogLock
{
- private static readonly ILog log = LogManager.GetLogger(typeof(LogLock));
static ReaderWriterLockSlim LogWriteLock = new ReaderWriterLockSlim();
static int WritedCount = 0;
static int FailedCount = 0;
@@ -53,12 +52,14 @@ public static void OutLogAOP(string prefix, string traceId, string[] dataParas,
default:
break;
}
+
if (AppSettings.app(new string[] { AppSetingNodeName, AppSetingName, "Enabled" }).ObjToBool())
{
if (AppSettings.app(new string[] { AppSetingNodeName, AppSetingName, "LogToDB", "Enabled" }).ObjToBool())
{
OutSql2LogToDB(prefix, traceId, dataParas, IsHeader);
}
+
if (AppSettings.app(new string[] { AppSetingNodeName, AppSetingName, "LogToFile", "Enabled" }).ObjToBool())
{
OutSql2LogToFile(prefix, traceId, dataParas, IsHeader);
@@ -90,6 +91,7 @@ public static void OutSql2LogToFile(string prefix, string traceId, string[] data
{
Directory.CreateDirectory(folderPath);
}
+
//string logFilePath = Path.Combine(path, $@"{filename}.log");
var logFilePath = FileHelper.GetAvailableFileWithPrefixOrderSize(folderPath, prefix);
switch (prefix)
@@ -98,47 +100,48 @@ public static void OutSql2LogToFile(string prefix, string traceId, string[] data
AOPLogInfo apiLogAopInfo = JsonConvert.DeserializeObject(dataParas[1]);
//记录被拦截方法信息的日志信息
var dataIntercept = "" +
- $"【操作时间】:{apiLogAopInfo.RequestTime}\r\n" +
- $"【当前操作用户】:{ apiLogAopInfo.OpUserName} \r\n" +
- $"【当前执行方法】:{ apiLogAopInfo.RequestMethodName} \r\n" +
- $"【携带的参数有】: {apiLogAopInfo.RequestParamsName} \r\n" +
- $"【携带的参数JSON】: {apiLogAopInfo.RequestParamsData} \r\n" +
- $"【响应时间】:{apiLogAopInfo.ResponseIntervalTime}\r\n" +
- $"【执行完成时间】:{apiLogAopInfo.ResponseTime}\r\n" +
- $"【执行完成结果】:{apiLogAopInfo.ResponseJsonData}\r\n";
+ $"【操作时间】:{apiLogAopInfo.RequestTime}\r\n" +
+ $"【当前操作用户】:{apiLogAopInfo.OpUserName} \r\n" +
+ $"【当前执行方法】:{apiLogAopInfo.RequestMethodName} \r\n" +
+ $"【携带的参数有】: {apiLogAopInfo.RequestParamsName} \r\n" +
+ $"【携带的参数JSON】: {apiLogAopInfo.RequestParamsData} \r\n" +
+ $"【响应时间】:{apiLogAopInfo.ResponseIntervalTime}\r\n" +
+ $"【执行完成时间】:{apiLogAopInfo.ResponseTime}\r\n" +
+ $"【执行完成结果】:{apiLogAopInfo.ResponseJsonData}\r\n";
dataParas = new string[] { dataIntercept };
break;
case "AOPLogEx":
AOPLogExInfo apiLogAopExInfo = JsonConvert.DeserializeObject(dataParas[1]);
var dataInterceptEx = "" +
- $"【操作时间】:{apiLogAopExInfo.ApiLogAopInfo.RequestTime}\r\n" +
- $"【当前操作用户】:{ apiLogAopExInfo.ApiLogAopInfo.OpUserName} \r\n" +
- $"【当前执行方法】:{ apiLogAopExInfo.ApiLogAopInfo.RequestMethodName} \r\n" +
- $"【携带的参数有】: {apiLogAopExInfo.ApiLogAopInfo.RequestParamsName} \r\n" +
- $"【携带的参数JSON】: {apiLogAopExInfo.ApiLogAopInfo.RequestParamsData} \r\n" +
- $"【响应时间】:{apiLogAopExInfo.ApiLogAopInfo.ResponseIntervalTime}\r\n" +
- $"【执行完成时间】:{apiLogAopExInfo.ApiLogAopInfo.ResponseTime}\r\n" +
- $"【执行完成结果】:{apiLogAopExInfo.ApiLogAopInfo.ResponseJsonData}\r\n" +
- $"【执行完成异常信息】:方法中出现异常:{apiLogAopExInfo.ExMessage}\r\n" +
- $"【执行完成异常】:方法中出现异常:{apiLogAopExInfo.InnerException}\r\n";
+ $"【操作时间】:{apiLogAopExInfo.ApiLogAopInfo.RequestTime}\r\n" +
+ $"【当前操作用户】:{apiLogAopExInfo.ApiLogAopInfo.OpUserName} \r\n" +
+ $"【当前执行方法】:{apiLogAopExInfo.ApiLogAopInfo.RequestMethodName} \r\n" +
+ $"【携带的参数有】: {apiLogAopExInfo.ApiLogAopInfo.RequestParamsName} \r\n" +
+ $"【携带的参数JSON】: {apiLogAopExInfo.ApiLogAopInfo.RequestParamsData} \r\n" +
+ $"【响应时间】:{apiLogAopExInfo.ApiLogAopInfo.ResponseIntervalTime}\r\n" +
+ $"【执行完成时间】:{apiLogAopExInfo.ApiLogAopInfo.ResponseTime}\r\n" +
+ $"【执行完成结果】:{apiLogAopExInfo.ApiLogAopInfo.ResponseJsonData}\r\n" +
+ $"【执行完成异常信息】:方法中出现异常:{apiLogAopExInfo.ExMessage}\r\n" +
+ $"【执行完成异常】:方法中出现异常:{apiLogAopExInfo.InnerException}\r\n";
dataParas = new string[] { dataInterceptEx };
break;
}
+
var now = DateTime.Now;
string logContent = String.Join("\r\n", dataParas);
if (IsHeader)
{
logContent = (
- "--------------------------------\r\n" +
- DateTime.Now + "|\r\n" +
- String.Join("\r\n", dataParas) + "\r\n"
- );
+ "--------------------------------\r\n" +
+ DateTime.Now + "|\r\n" +
+ String.Join("\r\n", dataParas) + "\r\n"
+ );
}
else
{
logContent = (
- dataParas[1] + ",\r\n"
- );
+ dataParas[1] + ",\r\n"
+ );
}
//if (logContent.IsNotEmptyOrNull() && logContent.Length > 500)
@@ -148,12 +151,12 @@ public static void OutSql2LogToFile(string prefix, string traceId, string[] data
if (isWrt)
{
File.WriteAllText(logFilePath, logContent);
-
}
else
{
File.AppendAllText(logFilePath, logContent);
}
+
WritedCount++;
}
catch (Exception e)
@@ -170,14 +173,15 @@ public static void OutSql2LogToFile(string prefix, string traceId, string[] data
LogWriteLock.ExitWriteLock();
}
}
+
public static void OutSql2LogToDB(string prefix, string traceId, string[] dataParas, bool IsHeader = true)
{
- log4net.LogicalThreadContext.Properties["LogType"] = prefix;
- log4net.LogicalThreadContext.Properties["TraceId"] = traceId;
- if (dataParas.Length >= 2)
- {
- log4net.LogicalThreadContext.Properties["DataType"] = dataParas[0];
- }
+ //log4net.LogicalThreadContext.Properties["LogType"] = prefix;
+ //log4net.LogicalThreadContext.Properties["TraceId"] = traceId;
+ //if (dataParas.Length >= 2)
+ //{
+ // log4net.LogicalThreadContext.Properties["DataType"] = dataParas[0];
+ //}
dataParas = dataParas.Skip(1).ToArray();
@@ -186,32 +190,37 @@ public static void OutSql2LogToDB(string prefix, string traceId, string[] dataPa
{
logContent = (String.Join("", dataParas));
}
+
switch (prefix)
{
//DEBUG | INFO | WARN | ERROR | FATAL
case "AOPLog":
- log.Info(logContent);
+ //TODO 是否需要输出?
+ //Log.Information(logContent);
break;
case "AOPLogEx":
- log.Error(logContent);
+ Log.Error(logContent);
break;
case "RequestIpInfoLog":
- log.Debug(logContent);
+ //TODO 是否需要Debug输出?
+ //Log.Debug(logContent);
break;
case "RecordAccessLogs":
- log.Debug(logContent);
+ //TODO 是否需要Debug输出?
+ //Log.Debug(logContent);
break;
case "SqlLog":
- log.Info(logContent);
+ Log.Information(logContent);
break;
case "RequestResponseLog":
- log.Debug(logContent);
+ //TODO 是否需要Debug输出?
+ //Log.Debug(logContent);
break;
default:
break;
}
-
}
+
///
/// 读取文件内容
///
@@ -287,6 +296,7 @@ public static string ReadLog(string folderPath, string fileName, Encoding encode
{
LogWriteLock.ExitReadLock();
}
+
return s;
}
@@ -315,7 +325,6 @@ private static List GetRequestInfo(ReadType readType)
}
}
}
-
}
return requestInfos;
@@ -336,16 +345,18 @@ public static List GetLogData()
if (!string.IsNullOrEmpty(aoplogContent))
{
aopLogs = aoplogContent.Split("--------------------------------")
- .Where(d => !string.IsNullOrEmpty(d) && d != "\n" && d != "\r\n")
- .Select(d => new LogInfo
- {
- Datetime = d.Split("|")[0].ObjToDate(),
- Content = d.Split("|")[1]?.Replace("\r\n", "
"),
- LogColor = "AOP",
- }).ToList();
+ .Where(d => !string.IsNullOrEmpty(d) && d != "\n" && d != "\r\n")
+ .Select(d => new LogInfo
+ {
+ Datetime = d.Split("|")[0].ObjToDate(),
+ Content = d.Split("|")[1]?.Replace("\r\n", "
"),
+ LogColor = "AOP",
+ }).ToList();
}
}
- catch (Exception) { }
+ catch (Exception)
+ {
+ }
try
{
@@ -354,17 +365,19 @@ public static List GetLogData()
if (!string.IsNullOrEmpty(exclogContent))
{
excLogs = exclogContent.Split("--------------------------------")
- .Where(d => !string.IsNullOrEmpty(d) && d != "\n" && d != "\r\n")
- .Select(d => new LogInfo
- {
- Datetime = (d.Split("|")[0]).Split(',')[0].ObjToDate(),
- Content = d.Split("|")[1]?.Replace("\r\n", "
"),
- LogColor = "EXC",
- Import = 9,
- }).ToList();
+ .Where(d => !string.IsNullOrEmpty(d) && d != "\n" && d != "\r\n")
+ .Select(d => new LogInfo
+ {
+ Datetime = (d.Split("|")[0]).Split(',')[0].ObjToDate(),
+ Content = d.Split("|")[1]?.Replace("\r\n", "
"),
+ LogColor = "EXC",
+ Import = 9,
+ }).ToList();
}
}
- catch (Exception) { }
+ catch (Exception)
+ {
+ }
try
@@ -374,16 +387,18 @@ public static List GetLogData()
if (!string.IsNullOrEmpty(sqllogContent))
{
sqlLogs = sqllogContent.Split("--------------------------------")
- .Where(d => !string.IsNullOrEmpty(d) && d != "\n" && d != "\r\n")
- .Select(d => new LogInfo
- {
- Datetime = d.Split("|")[0].ObjToDate(),
- Content = d.Split("|")[1]?.Replace("\r\n", "
"),
- LogColor = "SQL",
- }).ToList();
+ .Where(d => !string.IsNullOrEmpty(d) && d != "\n" && d != "\r\n")
+ .Select(d => new LogInfo
+ {
+ Datetime = d.Split("|")[0].ObjToDate(),
+ Content = d.Split("|")[1]?.Replace("\r\n", "
"),
+ LogColor = "SQL",
+ }).ToList();
}
}
- catch (Exception) { }
+ catch (Exception)
+ {
+ }
//try
//{
@@ -422,14 +437,17 @@ public static List GetLogData()
{
aopLogs.AddRange(excLogs);
}
+
if (sqlLogs != null)
{
aopLogs.AddRange(sqlLogs);
}
+
if (reqresLogs != null)
{
aopLogs.AddRange(reqresLogs);
}
+
aopLogs = aopLogs.OrderByDescending(d => d.Import).ThenByDescending(d => d.Datetime).Take(100).ToList();
return aopLogs;
@@ -450,7 +468,8 @@ public static RequestApiWeekView RequestApiinfoByWeek()
Logs = GetRequestInfo(ReadType.Prefix);
apiWeeks = (from n in Logs
- group n by new { n.Week, n.Url } into g
+ group n by new { n.Week, n.Url }
+ into g
select new ApiWeek
{
week = g.Key.Week,
@@ -459,7 +478,6 @@ public static RequestApiWeekView RequestApiinfoByWeek()
}).ToList();
//apiWeeks = apiWeeks.OrderByDescending(d => d.count).Take(8).ToList();
-
}
catch (Exception)
{
@@ -489,10 +507,12 @@ public static RequestApiWeekView RequestApiinfoByWeek()
jsonBuilder.Append(item.count);
jsonBuilder.Append("\",");
}
+
if (apiweeksCurrentWeek.Count > 0)
{
jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
}
+
jsonBuilder.Append("},");
}
@@ -500,6 +520,7 @@ public static RequestApiWeekView RequestApiinfoByWeek()
{
jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
}
+
jsonBuilder.Append("]");
//columns.AddRange(apiWeeks.OrderByDescending(d => d.count).Take(8).Select(d => d.url).ToList());
@@ -521,7 +542,8 @@ public static AccessApiDateView AccessApiByDate()
Logs = GetRequestInfo(ReadType.Prefix);
apiDates = (from n in Logs
- group n by new { n.Date } into g
+ group n by new { n.Date }
+ into g
select new ApiDate
{
date = g.Key.Date,
@@ -529,7 +551,6 @@ public static AccessApiDateView AccessApiByDate()
}).ToList();
apiDates = apiDates.OrderByDescending(d => d.date).Take(7).ToList();
-
}
catch (Exception)
{
@@ -552,7 +573,8 @@ public static AccessApiDateView AccessApiByHour()
apiDates = (from n in Logs
where n.Datetime.ObjToDate() >= DateTime.Today
- group n by new { hour = n.Datetime.ObjToDate().Hour } into g
+ group n by new { hour = n.Datetime.ObjToDate().Hour }
+ into g
select new ApiDate
{
date = g.Key.hour.ToString("00"),
@@ -560,7 +582,6 @@ where n.Datetime.ObjToDate() >= DateTime.Today
}).ToList();
apiDates = apiDates.OrderBy(d => d.date).Take(24).ToList();
-
}
catch (Exception)
{
@@ -580,14 +601,15 @@ public enum ReadType
/// 精确查找一个
///
Accurate,
+
///
/// 指定前缀,模糊查找全部
///
Prefix,
+
///
/// 指定前缀,最新一个文件
///
PrefixLatest
}
-
-}
+}
\ No newline at end of file
diff --git a/Blog.Core.Extensions/Blog.Core.Extensions.csproj b/Blog.Core.Extensions/Blog.Core.Extensions.csproj
index 451d24f1..9eae3d92 100644
--- a/Blog.Core.Extensions/Blog.Core.Extensions.csproj
+++ b/Blog.Core.Extensions/Blog.Core.Extensions.csproj
@@ -18,10 +18,10 @@
-
+
@@ -35,6 +35,7 @@
+
diff --git a/Blog.Core.Extensions/Middlewares/ExceptionHandlerMiddleware.cs b/Blog.Core.Extensions/Middlewares/ExceptionHandlerMiddleware.cs
index 85d96e9b..aed57769 100644
--- a/Blog.Core.Extensions/Middlewares/ExceptionHandlerMiddleware.cs
+++ b/Blog.Core.Extensions/Middlewares/ExceptionHandlerMiddleware.cs
@@ -4,14 +4,13 @@
using Blog.Core.Model;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
+using Serilog;
namespace Blog.Core.Extensions.Middlewares
{
public class ExceptionHandlerMiddleware
{
private readonly RequestDelegate _next;
- private static readonly log4net.ILog Log =
- log4net.LogManager.GetLogger(typeof(ExceptionHandlerMiddleware));
public ExceptionHandlerMiddleware(RequestDelegate next)
{
@@ -48,7 +47,9 @@ private static async Task WriteExceptionAsync(HttpContext context, Exception e)
context.Response.ContentType = "application/json";
- await context.Response.WriteAsync(JsonConvert.SerializeObject((new ApiResponse(StatusCode.CODE500, e.Message)).MessageModel)).ConfigureAwait(false);
+ await context.Response
+ .WriteAsync(JsonConvert.SerializeObject(new ApiResponse(StatusCode.CODE500, e.Message).MessageModel))
+ .ConfigureAwait(false);
}
}
-}
+}
\ No newline at end of file
diff --git a/Blog.Core.Extensions/Middlewares/IpLimitMiddleware.cs b/Blog.Core.Extensions/Middlewares/IpLimitMiddleware.cs
index 958d6ff3..7fe68fc4 100644
--- a/Blog.Core.Extensions/Middlewares/IpLimitMiddleware.cs
+++ b/Blog.Core.Extensions/Middlewares/IpLimitMiddleware.cs
@@ -1,8 +1,8 @@
-using System;
-using AspNetCoreRateLimit;
+using AspNetCoreRateLimit;
using Blog.Core.Common;
-using log4net;
using Microsoft.AspNetCore.Builder;
+using System;
+using Serilog;
namespace Blog.Core.Extensions.Middlewares
{
@@ -11,7 +11,6 @@ namespace Blog.Core.Extensions.Middlewares
///
public static class IpLimitMiddleware
{
- private static readonly ILog Log = LogManager.GetLogger(typeof(IpLimitMiddleware));
public static void UseIpLimitMiddle(this IApplicationBuilder app)
{
if (app == null) throw new ArgumentNullException(nameof(app));
diff --git a/Blog.Core.Extensions/Middlewares/IpLogMiddleware.cs b/Blog.Core.Extensions/Middlewares/IpLogMiddleware.cs
index b6b91bd5..ccd0d7af 100644
--- a/Blog.Core.Extensions/Middlewares/IpLogMiddleware.cs
+++ b/Blog.Core.Extensions/Middlewares/IpLogMiddleware.cs
@@ -1,10 +1,10 @@
-using System;
-using System.Threading.Tasks;
-using Blog.Core.Common;
+using Blog.Core.Common;
using Blog.Core.Common.LogHelper;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
+using System;
+using System.Threading.Tasks;
namespace Blog.Core.Extensions.Middlewares
{
@@ -19,7 +19,6 @@ public class IpLogMiddleware
///
private readonly RequestDelegate _next;
private readonly IWebHostEnvironment _environment;
- private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(IpLogMiddleware));
///
///
diff --git a/Blog.Core.Extensions/Middlewares/MiniProfilerMiddleware.cs b/Blog.Core.Extensions/Middlewares/MiniProfilerMiddleware.cs
index 068c4a0d..49e3b70d 100644
--- a/Blog.Core.Extensions/Middlewares/MiniProfilerMiddleware.cs
+++ b/Blog.Core.Extensions/Middlewares/MiniProfilerMiddleware.cs
@@ -1,7 +1,7 @@
-using System;
-using Blog.Core.Common;
-using log4net;
+using Blog.Core.Common;
using Microsoft.AspNetCore.Builder;
+using System;
+using Serilog;
namespace Blog.Core.Extensions.Middlewares
{
@@ -10,7 +10,6 @@ namespace Blog.Core.Extensions.Middlewares
///
public static class MiniProfilerMiddleware
{
- private static readonly ILog Log = LogManager.GetLogger(typeof(MiniProfilerMiddleware));
public static void UseMiniProfilerMiddleware(this IApplicationBuilder app)
{
if (app == null) throw new ArgumentNullException(nameof(app));
diff --git a/Blog.Core.Extensions/Middlewares/SignalRSendMiddleware.cs b/Blog.Core.Extensions/Middlewares/SignalRSendMiddleware.cs
index 1909c08f..f15df7b4 100644
--- a/Blog.Core.Extensions/Middlewares/SignalRSendMiddleware.cs
+++ b/Blog.Core.Extensions/Middlewares/SignalRSendMiddleware.cs
@@ -36,6 +36,7 @@ public async Task InvokeAsync(HttpContext context)
{
if (AppSettings.app("Middleware", "SignalR", "Enabled").ObjToBool())
{
+ //TODO 主动发送错误消息
await _hubContext.Clients.All.SendAsync("ReceiveUpdate", LogLock.GetLogData());
}
await _next(context);
diff --git a/Blog.Core.Extensions/Middlewares/SwaggerMiddleware.cs b/Blog.Core.Extensions/Middlewares/SwaggerMiddleware.cs
index 099b2576..73af77d2 100644
--- a/Blog.Core.Extensions/Middlewares/SwaggerMiddleware.cs
+++ b/Blog.Core.Extensions/Middlewares/SwaggerMiddleware.cs
@@ -1,10 +1,10 @@
-using System;
-using System.IO;
-using System.Linq;
-using Blog.Core.Common;
-using log4net;
+using Blog.Core.Common;
using Microsoft.AspNetCore.Builder;
using Swashbuckle.AspNetCore.SwaggerUI;
+using System;
+using System.IO;
+using System.Linq;
+using Serilog;
using static Blog.Core.Extensions.CustomApiVersion;
namespace Blog.Core.Extensions.Middlewares
@@ -14,7 +14,6 @@ namespace Blog.Core.Extensions.Middlewares
///
public static class SwaggerMiddleware
{
- private static readonly ILog Log = LogManager.GetLogger(typeof(SwaggerMiddleware));
public static void UseSwaggerMiddle(this IApplicationBuilder app, Func streamHtml)
{
if (app == null) throw new ArgumentNullException(nameof(app));
@@ -24,10 +23,7 @@ public static void UseSwaggerMiddle(this IApplicationBuilder app, Func s
{
//根据版本名称倒序 遍历展示
var apiName = AppSettings.app(new string[] { "Startup", "ApiName" });
- typeof(ApiVersions).GetEnumNames().OrderByDescending(e => e).ToList().ForEach(version =>
- {
- c.SwaggerEndpoint($"/swagger/{version}/swagger.json", $"{apiName} {version}");
- });
+ typeof(ApiVersions).GetEnumNames().OrderByDescending(e => e).ToList().ForEach(version => { c.SwaggerEndpoint($"/swagger/{version}/swagger.json", $"{apiName} {version}"); });
c.SwaggerEndpoint($"https://petstore.swagger.io/v2/swagger.json", $"{apiName} pet");
@@ -38,12 +34,13 @@ public static void UseSwaggerMiddle(this IApplicationBuilder app, Func s
Log.Error(msg);
throw new Exception(msg);
}
+
c.IndexStream = streamHtml;
c.DocExpansion(DocExpansion.None); //->修改界面打开时自动折叠
if (Permissions.IsUseIds4)
{
- c.OAuthClientId("blogadminjs");
+ c.OAuthClientId("blogadminjs");
}
@@ -52,4 +49,4 @@ public static void UseSwaggerMiddle(this IApplicationBuilder app, Func s
});
}
}
-}
+}
\ No newline at end of file
diff --git a/Blog.Core.Extensions/ServiceExtensions/AppConfigSetup.cs b/Blog.Core.Extensions/ServiceExtensions/AppConfigSetup.cs
index 0622e766..0336567f 100644
--- a/Blog.Core.Extensions/ServiceExtensions/AppConfigSetup.cs
+++ b/Blog.Core.Extensions/ServiceExtensions/AppConfigSetup.cs
@@ -76,10 +76,10 @@ public static void AddAppConfigSetup(this IServiceCollection services, IHostEnvi
var ipLogOpen = AppSettings.app(new string[] { "Middleware", "IPLog", "Enabled" }).ObjToBool();
var recordAccessLogsOpen = AppSettings.app(new string[] { "Middleware", "RecordAccessLogs", "Enabled" }).ObjToBool();
ConsoleHelper.WriteSuccessLine($"OPEN Log: " +
- (requestResponseLogOpen ? "RequestResponseLog √," : "") +
- (ipLogOpen ? "IPLog √," : "") +
- (recordAccessLogsOpen ? "RecordAccessLogs √," : "")
- );
+ (requestResponseLogOpen ? "RequestResponseLog √," : "") +
+ (ipLogOpen ? "IPLog √," : "") +
+ (recordAccessLogsOpen ? "RecordAccessLogs √," : "")
+ );
// 事务AOP
if (!AppSettings.app(new string[] { "AppSettings", "TranAOP", "Enabled" }).ObjToBool())
@@ -213,7 +213,6 @@ public static void AddAppConfigSetup(this IServiceCollection services, IHostEnvi
Console.WriteLine();
}
-
}
public static void AddAppTableConfigSetup(this IServiceCollection services, IHostEnvironment env)
@@ -222,7 +221,6 @@ public static void AddAppTableConfigSetup(this IServiceCollection services, IHos
if (AppSettings.app(new string[] { "Startup", "AppConfigAlert", "Enabled" }).ObjToBool())
{
-
if (env.IsDevelopment())
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
@@ -230,6 +228,7 @@ public static void AddAppTableConfigSetup(this IServiceCollection services, IHos
}
#region 程序配置
+
List configInfos = new()
{
new string[] { "当前环境", Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") },
@@ -238,7 +237,7 @@ public static void AddAppTableConfigSetup(this IServiceCollection services, IHos
new string[] { "RabbitMQ消息列队", AppSettings.app("RabbitMQ", "Enabled") },
new string[] { "事件总线(必须开启消息列队)", AppSettings.app("EventBus", "Enabled") },
new string[] { "redis消息队列", AppSettings.app("Startup", "RedisMq", "Enabled") },
- new string[] { "是否多库", AppSettings.app("MutiDBEnabled" ) },
+ new string[] { "是否多库", AppSettings.app("MutiDBEnabled") },
new string[] { "读写分离", AppSettings.app("CQRSEnabled") },
};
@@ -253,17 +252,19 @@ public static void AddAppTableConfigSetup(this IServiceCollection services, IHos
TableStyle = TableStyle.Alternative
}.Writer(ConsoleColor.Blue);
Console.WriteLine();
+
#endregion 程序配置
#region AOP
+
List aopInfos = new()
-{
+ {
new string[] { "Redis缓存AOP", AppSettings.app("AppSettings", "RedisCachingAOP", "Enabled") },
new string[] { "内存缓存AOP", AppSettings.app("AppSettings", "MemoryCachingAOP", "Enabled") },
- new string[] { "服务日志AOP", AppSettings.app("AppSettings", "LogAOP", "Enabled" ) },
- new string[] { "事务AOP", AppSettings.app("AppSettings", "TranAOP", "Enabled" ) },
- new string[] { "Sql执行AOP", AppSettings.app("AppSettings", "SqlAOP", "OutToLogFile", "Enabled" ) },
- new string[] { "Sql执行AOP控制台输出", AppSettings.app("AppSettings", "SqlAOP", "OutToConsole", "Enabled" ) },
+ new string[] { "服务日志AOP", AppSettings.app("AppSettings", "LogAOP", "Enabled") },
+ new string[] { "事务AOP", AppSettings.app("AppSettings", "TranAOP", "Enabled") },
+ new string[] { "Sql执行AOP", AppSettings.app("AppSettings", "SqlAOP", "Enabled") },
+ new string[] { "Sql执行AOP控制台输出", AppSettings.app("AppSettings", "SqlAOP", "LogToConsole", "Enabled") },
};
new ConsoleTable
@@ -277,15 +278,17 @@ public static void AddAppTableConfigSetup(this IServiceCollection services, IHos
TableStyle = TableStyle.Alternative
}.Writer(ConsoleColor.Blue);
Console.WriteLine();
+
#endregion AOP
#region 中间件
+
List MiddlewareInfos = new()
{
new string[] { "请求纪录中间件", AppSettings.app("Middleware", "RecordAccessLogs", "Enabled") },
- new string[] { "IP记录中间件", AppSettings.app("Middleware", "IPLog", "Enabled" ) },
- new string[] { "请求响应日志中间件", AppSettings.app("Middleware", "RequestResponseLog", "Enabled" ) },
- new string[] { "SingnalR实时发送请求数据中间件", AppSettings.app("Middleware", "SignalR", "Enabled" ) },
+ new string[] { "IP记录中间件", AppSettings.app("Middleware", "IPLog", "Enabled") },
+ new string[] { "请求响应日志中间件", AppSettings.app("Middleware", "RequestResponseLog", "Enabled") },
+ new string[] { "SingnalR实时发送请求数据中间件", AppSettings.app("Middleware", "SignalR", "Enabled") },
new string[] { "IP限流中间件", AppSettings.app("Middleware", "IpRateLimit", "Enabled") },
new string[] { "性能分析中间件", AppSettings.app("Startup", "MiniProfiler", "Enabled") },
new string[] { "Consul注册服务", AppSettings.app("Middleware", "Consul", "Enabled") },
@@ -302,10 +305,9 @@ public static void AddAppTableConfigSetup(this IServiceCollection services, IHos
TableStyle = TableStyle.Alternative
}.Writer(ConsoleColor.Blue);
Console.WriteLine();
- #endregion 中间件
+ #endregion 中间件
}
-
}
}
-}
+}
\ No newline at end of file
diff --git a/Blog.Core.Extensions/ServiceExtensions/AutofacModuleRegister.cs b/Blog.Core.Extensions/ServiceExtensions/AutofacModuleRegister.cs
index 7f2997bd..4351962b 100644
--- a/Blog.Core.Extensions/ServiceExtensions/AutofacModuleRegister.cs
+++ b/Blog.Core.Extensions/ServiceExtensions/AutofacModuleRegister.cs
@@ -6,20 +6,18 @@
using Blog.Core.IServices.BASE;
using Blog.Core.Model;
using Blog.Core.Repository.Base;
+using Blog.Core.Repository.UnitOfWorks;
using Blog.Core.Services.BASE;
-using log4net;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
-using Blog.Core.Repository.UnitOfWorks;
+using Serilog;
namespace Blog.Core.Extensions
{
public class AutofacModuleRegister : Autofac.Module
{
- private static readonly ILog log = LogManager.GetLogger(typeof(AutofacModuleRegister));
-
protected override void Load(ContainerBuilder builder)
{
var basePath = AppContext.BaseDirectory;
@@ -34,39 +32,39 @@ protected override void Load(ContainerBuilder builder)
if (!(File.Exists(servicesDllFile) && File.Exists(repositoryDllFile)))
{
var msg = "Repository.dll和service.dll 丢失,因为项目解耦了,所以需要先F6编译,再F5运行,请检查 bin 文件夹,并拷贝。";
- log.Error(msg);
+ Log.Error(msg);
throw new Exception(msg);
}
// AOP 开关,如果想要打开指定的功能,只需要在 appsettigns.json 对应对应 true 就行。
var cacheType = new List();
- if (AppSettings.app(new string[] {"AppSettings", "RedisCachingAOP", "Enabled"}).ObjToBool())
+ if (AppSettings.app(new string[] { "AppSettings", "RedisCachingAOP", "Enabled" }).ObjToBool())
{
builder.RegisterType();
cacheType.Add(typeof(BlogRedisCacheAOP));
}
- if (AppSettings.app(new string[] {"AppSettings", "MemoryCachingAOP", "Enabled"}).ObjToBool())
+ if (AppSettings.app(new string[] { "AppSettings", "MemoryCachingAOP", "Enabled" }).ObjToBool())
{
builder.RegisterType();
cacheType.Add(typeof(BlogCacheAOP));
}
- if (AppSettings.app(new string[] {"AppSettings", "TranAOP", "Enabled"}).ObjToBool())
+ if (AppSettings.app(new string[] { "AppSettings", "TranAOP", "Enabled" }).ObjToBool())
{
builder.RegisterType();
cacheType.Add(typeof(BlogTranAOP));
}
- if (AppSettings.app(new string[] {"AppSettings", "LogAOP", "Enabled"}).ObjToBool())
+ if (AppSettings.app(new string[] { "AppSettings", "LogAOP", "Enabled" }).ObjToBool())
{
builder.RegisterType();
cacheType.Add(typeof(BlogLogAOP));
}
- builder.RegisterGeneric(typeof(BaseRepository<>)).As(typeof(IBaseRepository<>)).InstancePerDependency();//注册仓储
- builder.RegisterGeneric(typeof(BaseServices<>)).As(typeof(IBaseServices<>)).InstancePerDependency();//注册服务
+ builder.RegisterGeneric(typeof(BaseRepository<>)).As(typeof(IBaseRepository<>)).InstancePerDependency(); //注册仓储
+ builder.RegisterGeneric(typeof(BaseServices<>)).As(typeof(IBaseServices<>)).InstancePerDependency(); //注册服务
// 获取 Service.dll 程序集服务,并注册
var assemblysServices = Assembly.LoadFrom(servicesDllFile);
diff --git a/Blog.Core.Extensions/ServiceExtensions/HttpPollySetup.cs b/Blog.Core.Extensions/ServiceExtensions/HttpPollySetup.cs
index e8e3929f..b3147ca8 100644
--- a/Blog.Core.Extensions/ServiceExtensions/HttpPollySetup.cs
+++ b/Blog.Core.Extensions/ServiceExtensions/HttpPollySetup.cs
@@ -1,4 +1,4 @@
-using Blog.Core.Common.HttpPolly;
+using Blog.Core.Common.Https.HttpPolly;
using Blog.Core.Model;
using Microsoft.Extensions.DependencyInjection;
using Polly;
diff --git a/Blog.Core.Extensions/ServiceExtensions/SerilogSetup.cs b/Blog.Core.Extensions/ServiceExtensions/SerilogSetup.cs
new file mode 100644
index 00000000..a112409c
--- /dev/null
+++ b/Blog.Core.Extensions/ServiceExtensions/SerilogSetup.cs
@@ -0,0 +1,37 @@
+using Blog.Core.Common;
+using Blog.Core.Common.LogHelper;
+using Blog.Core.Serilog.Extensions;
+using Microsoft.Extensions.Hosting;
+using Serilog;
+using Serilog.Debugging;
+using System;
+using System.IO;
+
+namespace Blog.Core.Extensions.ServiceExtensions;
+
+public static class SerilogSetup
+{
+ public static IHostBuilder AddSerilogSetup(this IHostBuilder host)
+ {
+ if (host == null) throw new ArgumentNullException(nameof(host));
+
+ var loggerConfiguration = new LoggerConfiguration()
+ .ReadFrom.Configuration(AppSettings.Configuration)
+ .Enrich.FromLogContext()
+ //输出到控制台
+ .WriteToConsole()
+ //将日志保存到文件中
+ .WriteToFile();
+ //配置日志库
+ //.WriteToLogBatching();
+
+ Log.Logger = loggerConfiguration.CreateLogger();
+
+ //Serilog 内部日志
+ var file = File.CreateText(LogContextStatic.Combine($"SerilogDebug{DateTime.Now:yyyyMMdd}.txt"));
+ SelfLog.Enable(TextWriter.Synchronized(file));
+
+ host.UseSerilog();
+ return host;
+ }
+}
\ No newline at end of file
diff --git a/Blog.Core.Extensions/ServiceExtensions/SqlsugarSetup.cs b/Blog.Core.Extensions/ServiceExtensions/SqlsugarSetup.cs
index 3ecf224a..3440b8af 100644
--- a/Blog.Core.Extensions/ServiceExtensions/SqlsugarSetup.cs
+++ b/Blog.Core.Extensions/ServiceExtensions/SqlsugarSetup.cs
@@ -1,6 +1,7 @@
using Blog.Core.Common;
+using Blog.Core.Common.Const;
using Blog.Core.Common.DB;
-using Blog.Core.Common.Helper;
+using Blog.Core.Common.DB.Aop;
using Blog.Core.Common.LogHelper;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;
@@ -9,7 +10,6 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
-using Blog.Core.Common.DB.Aop;
namespace Blog.Core.Extensions
{
@@ -48,7 +48,7 @@ public static void AddSqlsugarSetup(this IServiceCollection services)
BaseDBConfig.MutiConnectionString.allDbs.ForEach(m =>
{
- listConfig.Add(new ConnectionConfig()
+ var config = new ConnectionConfig()
{
ConfigId = m.ConnId.ObjToString().ToLower(),
ConnectionString = m.Connection,
@@ -56,29 +56,6 @@ public static void AddSqlsugarSetup(this IServiceCollection services)
IsAutoCloseConnection = true,
// Check out more information: https://github.com/anjoy8/Blog.Core/issues/122
//IsShardSameThread = false,
- AopEvents = new AopEvents
- {
- OnLogExecuting = (sql, p) =>
- {
- if (AppSettings.app(new string[] { "AppSettings", "SqlAOP", "Enabled" }).ObjToBool())
- {
- if (AppSettings.app(new string[] { "AppSettings", "SqlAOP", "LogToFile", "Enabled" }).ObjToBool())
- {
- Parallel.For(0, 1, e =>
- {
- MiniProfiler.Current.CustomTiming("SQL:", GetParas(p) + "【SQL语句】:" + sql);
- //LogLock.OutSql2Log("SqlLog", new string[] { GetParas(p), "【SQL语句】:" + sql });
- LogLock.OutLogAOP("SqlLog", "", new string[] { sql.GetType().ToString(), GetParas(p), "【SQL语句】:" + sql });
-
- });
- }
- if (AppSettings.app(new string[] { "AppSettings", "SqlAOP", "LogToConsole", "Enabled" }).ObjToBool())
- {
- ConsoleHelper.WriteColorLine(string.Join("\r\n", new string[] { "--------", $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} :" + GetWholeSql(p, sql) }), ConsoleColor.DarkCyan);
- }
- }
- },
- },
MoreSettings = new ConnMoreSettings()
{
//IsWithNoLockQuery = true,
@@ -99,15 +76,29 @@ public static void AddSqlsugarSetup(this IServiceCollection services)
}
},
InitKeyType = InitKeyType.Attribute
+ };
+ if (SqlSugarConst.LogConfigId.Equals(m.ConnId))
+ {
+ BaseDBConfig.LogConfig = config;
}
- );
+
+ listConfig.Add(config);
});
+
+ if (BaseDBConfig.LogConfig is null)
+ {
+ throw new ApplicationException("未配置Log库连接");
+ }
+
return new SqlSugarScope(listConfig, db =>
{
listConfig.ForEach(config =>
{
var dbProvider = db.GetConnectionScope((string)config.ConfigId);
+ // 打印SQL语句
+ dbProvider.Aop.OnLogExecuting = (s, parameters) => SqlSugarAop.OnLogExecuting(dbProvider,s, parameters, config);
+
// 数据审计
dbProvider.Aop.DataExecuting = SqlSugarAop.DataExecuting;
diff --git a/Blog.Core.Extensions/ServiceExtensions/SwaggerSetup.cs b/Blog.Core.Extensions/ServiceExtensions/SwaggerSetup.cs
index 449b6a4d..85dff620 100644
--- a/Blog.Core.Extensions/ServiceExtensions/SwaggerSetup.cs
+++ b/Blog.Core.Extensions/ServiceExtensions/SwaggerSetup.cs
@@ -1,7 +1,7 @@
using Blog.Core.Common;
-using log4net;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
+using Serilog;
using Swashbuckle.AspNetCore.Filters;
using System;
using System.Collections.Generic;
@@ -17,10 +17,6 @@ namespace Blog.Core.Extensions
///
public static class SwaggerSetup
{
-
- private static readonly ILog log =
- LogManager.GetLogger(typeof(SwaggerSetup));
-
public static void AddSwaggerSetup(this IServiceCollection services)
{
if (services == null) throw new ArgumentNullException(nameof(services));
@@ -59,7 +55,7 @@ public static void AddSwaggerSetup(this IServiceCollection services)
}
catch (Exception ex)
{
- log.Error("Blog.Core.xml和Blog.Core.Model.xml 丢失,请检查并拷贝。\n" + ex.Message);
+ Log.Error("Blog.Core.xml和Blog.Core.Model.xml 丢失,请检查并拷贝。\n" + ex.Message);
}
// 开启加权小锁
@@ -82,12 +78,13 @@ public static void AddSwaggerSetup(this IServiceCollection services)
Implicit = new OpenApiOAuthFlow
{
AuthorizationUrl = new Uri($"{AppSettings.app(new string[] { "Startup", "IdentityServer4", "AuthorizationUrl" })}/connect/authorize"),
- Scopes = new Dictionary {
+ Scopes = new Dictionary
{
- "blog.core.api","ApiResource id"
+ {
+ "blog.core.api", "ApiResource id"
+ }
}
}
- }
}
});
}
@@ -97,14 +94,11 @@ public static void AddSwaggerSetup(this IServiceCollection services)
c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
{
Description = "JWT授权(数据将在请求头中进行传输) 直接在下框中输入Bearer {token}(注意两者之间是一个空格)\"",
- Name = "Authorization",//jwt默认的参数名称
- In = ParameterLocation.Header,//jwt默认存放Authorization信息的位置(请求头中)
+ Name = "Authorization", //jwt默认的参数名称
+ In = ParameterLocation.Header, //jwt默认存放Authorization信息的位置(请求头中)
Type = SecuritySchemeType.ApiKey
});
}
-
-
-
});
services.AddSwaggerGenNewtonsoftSupport();
}
@@ -124,11 +118,11 @@ public enum ApiVersions
/// V1 版本
///
V1 = 1,
+
///
/// V2 版本
///
V2 = 2,
}
}
-
-}
+}
\ No newline at end of file
diff --git a/Blog.Core.Serilog.Es/Blog.Core.Serilog.Es.csproj b/Blog.Core.Serilog.Es/Blog.Core.Serilog.Es.csproj
index 5cf82020..398aab48 100644
--- a/Blog.Core.Serilog.Es/Blog.Core.Serilog.Es.csproj
+++ b/Blog.Core.Serilog.Es/Blog.Core.Serilog.Es.csproj
@@ -11,7 +11,7 @@
-
+
diff --git a/Blog.Core.Serilog/Blog.Core.Serilog.csproj b/Blog.Core.Serilog/Blog.Core.Serilog.csproj
new file mode 100644
index 00000000..07fa26f3
--- /dev/null
+++ b/Blog.Core.Serilog/Blog.Core.Serilog.csproj
@@ -0,0 +1,13 @@
+
+
+
+ net6.0
+ enable
+ enable
+
+
+
+
+
+
+
diff --git a/Blog.Core.Serilog/Extensions/LoggerConfigurationExtensions.cs b/Blog.Core.Serilog/Extensions/LoggerConfigurationExtensions.cs
new file mode 100644
index 00000000..2736aa1f
--- /dev/null
+++ b/Blog.Core.Serilog/Extensions/LoggerConfigurationExtensions.cs
@@ -0,0 +1,121 @@
+using Blog.Core.Common;
+using Blog.Core.Common.LogHelper;
+using Serilog;
+using Serilog.Events;
+using Serilog.Filters;
+using SqlSugar;
+
+namespace Blog.Core.Serilog.Extensions;
+
+public static class LoggerConfigurationExtensions
+{
+ public static LoggerConfiguration WriteToSqlServer(this LoggerConfiguration loggerConfiguration)
+ {
+ var logConnectionStrings = AppSettings.app("LogConnectionStrings");
+ if (logConnectionStrings.IsNullOrEmpty()) return loggerConfiguration;
+
+ //输出SQL
+ //loggerConfiguration = loggerConfiguration.WriteTo.Logger(lg =>
+ // lg.FilterSqlLog().WriteTo.MSSqlServer(logConnectionStrings, new MSSqlServerSinkOptions()
+ // {
+ // TableName = "SqlLog",
+ // AutoCreateSqlTable = true
+ // }));
+
+ //输出普通日志
+ //loggerConfiguration = loggerConfiguration.WriteTo.Logger(lg =>
+ // lg.FilterRemoveSqlLog().Filter.ByIncludingOnly(p => p.Level >= LogEventLevel.Error)
+ // .WriteTo.MSSqlServer(logConnectionStrings, new MSSqlServerSinkOptions()
+ // {
+ // TableName = "ErrorLog",
+ // AutoCreateSqlTable = true
+ // }));
+ //loggerConfiguration = loggerConfiguration.WriteTo.Logger(lg =>
+ // lg.FilterRemoveSqlLog().Filter.ByIncludingOnly(p => p.Level == LogEventLevel.Warning)
+ // .WriteTo.MSSqlServer(logConnectionStrings, new MSSqlServerSinkOptions()
+ // {
+ // TableName = "WarningLog",
+ // AutoCreateSqlTable = true
+ // }));
+ //loggerConfiguration = loggerConfiguration.WriteTo.Logger(lg =>
+ // lg.FilterRemoveSqlLog().Filter.ByIncludingOnly(p => p.Level <= LogEventLevel.Information)
+ // .WriteTo.MSSqlServer(logConnectionStrings, new MSSqlServerSinkOptions()
+ // {
+ // TableName = "InformationLog",
+ // AutoCreateSqlTable = true
+ // }));
+
+ return loggerConfiguration;
+ }
+
+ public static LoggerConfiguration WriteToConsole(this LoggerConfiguration loggerConfiguration)
+ {
+ //输出普通日志
+ loggerConfiguration = loggerConfiguration.WriteTo.Logger(lg =>
+ lg.FilterRemoveSqlLog().WriteTo.Console());
+
+ //输出SQL
+ loggerConfiguration = loggerConfiguration.WriteTo.Logger(lg =>
+ lg.FilterSqlLog().Filter.ByIncludingOnly(Matching.WithProperty(LogContextStatic.SqlOutToConsole, s => s))
+ .WriteTo.Console());
+
+ return loggerConfiguration;
+ }
+
+ public static LoggerConfiguration WriteToFile(this LoggerConfiguration loggerConfiguration)
+ {
+ //输出SQL
+ loggerConfiguration = loggerConfiguration.WriteTo.Logger(lg =>
+ lg.FilterSqlLog().Filter.ByIncludingOnly(Matching.WithProperty(LogContextStatic.SqlOutToFile, s => s))
+ .WriteTo.Async(s => s.File(LogContextStatic.Combine(LogContextStatic.AopSql, @"AopSql.txt"), rollingInterval: RollingInterval.Day,
+ outputTemplate: LogContextStatic.FileMessageTemplate, retainedFileCountLimit: 31)));
+ //输出普通日志
+ loggerConfiguration = loggerConfiguration.WriteTo.Logger(lg =>
+ lg.FilterRemoveSqlLog().WriteTo.Async(s => s.File(LogContextStatic.Combine(LogContextStatic.BasePathLogs, @"Log.txt"), rollingInterval: RollingInterval.Day,
+ outputTemplate: LogContextStatic.FileMessageTemplate, retainedFileCountLimit: 31)));
+ return loggerConfiguration;
+ }
+
+ public static LoggerConfiguration FilterSqlLog(this LoggerConfiguration lc)
+ {
+ lc = lc.Filter.ByIncludingOnly(Matching.WithProperty(LogContextStatic.LogSource, s => LogContextStatic.AopSql.Equals(s)));
+ return lc;
+ }
+
+ public static IEnumerable FilterSqlLog(this IEnumerable batch)
+ {
+ return batch.Where(s => s.WithProperty(LogContextStatic.LogSource, q => LogContextStatic.AopSql.Equals(q)))
+ .Where(s => s.WithProperty(LogContextStatic.SugarActionType,
+ q => !new[] { SugarActionType.UnKnown, SugarActionType.Query }.Contains(q)));
+ }
+
+ public static LoggerConfiguration FilterRemoveSqlLog(this LoggerConfiguration lc)
+ {
+ lc = lc.Filter.ByIncludingOnly(WithProperty(LogContextStatic.LogSource, s => !LogContextStatic.AopSql.Equals(s)));
+ return lc;
+ }
+
+ public static IEnumerable FilterRemoveOtherLog(this IEnumerable batch)
+ {
+ return batch.Where(s => WithProperty(LogContextStatic.LogSource,
+ q => !LogContextStatic.AopSql.Equals(q))(s));
+ }
+
+ public static Func WithProperty(string propertyName, Func predicate)
+ {
+ //如果不包含属性 也认为是true
+ return e =>
+ {
+ if (!e.Properties.TryGetValue(propertyName, out var propertyValue)) return true;
+
+ return propertyValue is ScalarValue { Value: T value } && predicate(value);
+ };
+ }
+
+ public static bool WithProperty(this LogEvent e, string key, Func predicate)
+ {
+ if (!e.Properties.TryGetValue(key, out var propertyValue)) return false;
+
+ return propertyValue is ScalarValue { Value: T value } && predicate(value);
+ }
+}
\ No newline at end of file
diff --git a/Blog.Core.Serilog/Utility/SerilogRequestUtility.cs b/Blog.Core.Serilog/Utility/SerilogRequestUtility.cs
new file mode 100644
index 00000000..cab7ae55
--- /dev/null
+++ b/Blog.Core.Serilog/Utility/SerilogRequestUtility.cs
@@ -0,0 +1,34 @@
+using Microsoft.AspNetCore.Http;
+using Serilog.Events;
+
+namespace Blog.Core.Serilog.Utility;
+
+public class SerilogRequestUtility
+{
+ private static readonly List _ignoreUrl = new()
+ {
+ "/job",
+ };
+
+ private static LogEventLevel DefaultGetLevel(
+ HttpContext ctx,
+ double _,
+ Exception? ex)
+ {
+ return ex is null && ctx.Response.StatusCode <= 499 ? LogEventLevel.Information : LogEventLevel.Error;
+ }
+
+ public static LogEventLevel GetRequestLevel(HttpContext ctx, double _, Exception? ex) =>
+ ex is null && ctx.Response.StatusCode <= 499 ? IgnoreRequest(ctx) : LogEventLevel.Error;
+
+ private static LogEventLevel IgnoreRequest(HttpContext ctx)
+ {
+ var path = ctx.Request.Path.Value;
+ if (path.IsNullOrEmpty())
+ {
+ return LogEventLevel.Information;
+ }
+
+ return _ignoreUrl.Any(s => path.StartsWith(s)) ? LogEventLevel.Verbose : LogEventLevel.Information;
+ }
+}
\ No newline at end of file
diff --git a/Blog.Core.Tasks/QuartzNet/Jobs/Job_AccessTrendLog_Quartz.cs b/Blog.Core.Tasks/QuartzNet/Jobs/Job_AccessTrendLog_Quartz.cs
index 1dcc57ed..1d501c34 100644
--- a/Blog.Core.Tasks/QuartzNet/Jobs/Job_AccessTrendLog_Quartz.cs
+++ b/Blog.Core.Tasks/QuartzNet/Jobs/Job_AccessTrendLog_Quartz.cs
@@ -34,7 +34,7 @@ public async Task Execute(IJobExecutionContext context)
}
public async Task Run(IJobExecutionContext context)
{
-
+
// 可以直接获取 JobDetail 的值
var jobKey = context.JobDetail.Key;
var jobId = jobKey.Name;
@@ -94,7 +94,7 @@ await _accessTrendLogServices.Add(new AccessTrendLog()
Parallel.For(0, 1, e =>
{
- LogLock.OutLogAOP("ACCESSTRENDLOG","",new string[] { activeUserVMs.GetType().ToString(), JsonConvert.SerializeObject(activeUserVMs) }, false);
+ LogLock.OutLogAOP("ACCESSTRENDLOG", "", new string[] { activeUserVMs.GetType().ToString(), JsonConvert.SerializeObject(activeUserVMs) }, false);
});
}
diff --git a/Blog.Core.Tasks/QuartzNet/Jobs/Job_OperateLog_Quartz.cs b/Blog.Core.Tasks/QuartzNet/Jobs/Job_OperateLog_Quartz.cs
index 18c4c298..abcd81ea 100644
--- a/Blog.Core.Tasks/QuartzNet/Jobs/Job_OperateLog_Quartz.cs
+++ b/Blog.Core.Tasks/QuartzNet/Jobs/Job_OperateLog_Quartz.cs
@@ -17,19 +17,21 @@ namespace Blog.Core.Tasks
{
public class Job_OperateLog_Quartz : JobBase, IJob
{
- private readonly IOperateLogServices _operateLogServices;
+ private readonly IOperateLogServices _operateLogServices;
private readonly IWebHostEnvironment _environment;
- public Job_OperateLog_Quartz(IOperateLogServices operateLogServices,IWebHostEnvironment environment, ITasksQzServices tasksQzServices,ITasksLogServices tasksLogServices)
- :base(tasksQzServices, tasksLogServices)
+ public Job_OperateLog_Quartz(IOperateLogServices operateLogServices, IWebHostEnvironment environment, ITasksQzServices tasksQzServices, ITasksLogServices tasksLogServices)
+ : base(tasksQzServices, tasksLogServices)
{
- _operateLogServices = operateLogServices;
- _environment = environment;
+ _operateLogServices = operateLogServices;
+ _environment = environment;
}
+
public async Task Execute(IJobExecutionContext context)
{
var executeLog = await ExecuteJob(context, async () => await Run(context));
}
+
public async Task Run(IJobExecutionContext context)
{
@@ -78,7 +80,4 @@ public async Task Run(IJobExecutionContext context)
}
}
}
-
-
-
-}
+}
\ No newline at end of file
diff --git a/Blog.Core.Tests/DependencyInjection/DI_Test.cs b/Blog.Core.Tests/DependencyInjection/DI_Test.cs
index ff2c74cd..d425fa01 100644
--- a/Blog.Core.Tests/DependencyInjection/DI_Test.cs
+++ b/Blog.Core.Tests/DependencyInjection/DI_Test.cs
@@ -59,7 +59,6 @@ public IContainer DICollections()
services.AddAutoMapper(typeof(Startup));
services.AddSingleton(new AppSettings(basePath));
- services.AddSingleton(new LogLock(basePath));
services.AddScoped();
services.AddScoped();
diff --git a/Blog.Core.sln b/Blog.Core.sln
index c8f61505..bf4f65cb 100644
--- a/Blog.Core.sln
+++ b/Blog.Core.sln
@@ -57,6 +57,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Blog.Core.Serilog.Es", "Blo
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Ocelot.Provider.Nacos", "Ocelot.Provider.Nacos\Ocelot.Provider.Nacos.csproj", "{6463FB13-5F01-4A1D-8B62-A454FB3812EB}"
EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Blog.Core.Serilog", "Blog.Core.Serilog\Blog.Core.Serilog.csproj", "{7F9057F0-ED8D-4694-B590-7D75C012DF00}"
+EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -119,6 +121,10 @@ Global
{6463FB13-5F01-4A1D-8B62-A454FB3812EB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6463FB13-5F01-4A1D-8B62-A454FB3812EB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6463FB13-5F01-4A1D-8B62-A454FB3812EB}.Release|Any CPU.Build.0 = Release|Any CPU
+ {7F9057F0-ED8D-4694-B590-7D75C012DF00}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {7F9057F0-ED8D-4694-B590-7D75C012DF00}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {7F9057F0-ED8D-4694-B590-7D75C012DF00}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {7F9057F0-ED8D-4694-B590-7D75C012DF00}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
From 070e441bc02ef0a1e410d176cf953e6549824721 Mon Sep 17 00:00:00 2001
From: anjoy8 <3143422472@qq.com>
Date: Sun, 2 Apr 2023 15:16:37 +0800
Subject: [PATCH 13/84] feat: :accept: change api param
---
Blog.Core.Api/Blog.Core.xml | 50 ++++++++---------
Blog.Core.Api/Controllers/BlogController.cs | 10 ++--
.../Controllers/DepartmentController.cs | 4 +-
Blog.Core.Api/Controllers/ModuleController.cs | 2 +-
.../Controllers/PermissionController.cs | 55 +++++++------------
Blog.Core.Api/Controllers/RoleController.cs | 2 +-
.../Controllers/TasksQzController.cs | 18 +++---
Blog.Core.Api/Controllers/TopicController.cs | 6 +-
.../Controllers/TopicDetailController.cs | 8 +--
.../Controllers/TransactionController.cs | 6 +-
Blog.Core.Api/Controllers/UserController.cs | 4 +-
.../Controllers/UserRoleController.cs | 2 +-
Blog.Core.Common/Helper/RecursionHelper.cs | 4 +-
Blog.Core.IServices/IBlogArticleServices.cs | 2 +-
Blog.Core.IServices/ITasksLogServices.cs | 4 +-
Blog.Core.IServices/IUserRoleServices.cs | 4 +-
Blog.Core.Model/ViewModels/BlogViewModels.cs | 2 +-
Blog.Core.Model/ViewModels/SysUserInfoDto.cs | 6 +-
Blog.Core.Services/BlogArticleServices.cs | 2 +-
Blog.Core.Services/TasksLogServices.cs | 4 +-
Blog.Core.Services/UserRoleServices.cs | 4 +-
.../Controller_Test/BlogController_Should.cs | 2 +-
22 files changed, 93 insertions(+), 108 deletions(-)
diff --git a/Blog.Core.Api/Blog.Core.xml b/Blog.Core.Api/Blog.Core.xml
index 79325e37..19f0ad64 100644
--- a/Blog.Core.Api/Blog.Core.xml
+++ b/Blog.Core.Api/Blog.Core.xml
@@ -26,14 +26,14 @@
-
+
获取博客详情
-
+
获取详情【无权限】
@@ -67,7 +67,7 @@
-
+
删除博客
@@ -276,7 +276,7 @@
-
+
删除一条接口
@@ -384,7 +384,7 @@
-
+
查询树形 Table
@@ -406,7 +406,7 @@
-
+
获取菜单树
@@ -428,7 +428,7 @@
-
+
通过角色获取菜单
@@ -442,7 +442,7 @@
-
+
删除菜单
@@ -456,7 +456,7 @@
-
+
系统接口菜单同步接口
@@ -493,7 +493,7 @@
-
+
删除角色
@@ -522,42 +522,42 @@
-
+
删除一个任务
-
+
启动计划任务
-
+
停止一个计划任务
-
+
暂停一个计划任务
-
+
恢复一个计划任务
-
+
重启一个计划任务
@@ -570,20 +570,20 @@
-
+
立即执行任务
-
+
获取任务运行日志
-
+
任务概况
@@ -629,7 +629,7 @@
-
+
获取详情【无权限】
@@ -650,14 +650,14 @@
-
+
删除 bug
-
+
测试事务在AOP中的使用
@@ -712,7 +712,7 @@
-
+
删除用户
@@ -748,7 +748,7 @@
-
+
新建用户角色关系
@@ -1203,7 +1203,7 @@
关键字
-
+
获取部门树
diff --git a/Blog.Core.Api/Controllers/BlogController.cs b/Blog.Core.Api/Controllers/BlogController.cs
index 83fad967..fbc67e12 100644
--- a/Blog.Core.Api/Controllers/BlogController.cs
+++ b/Blog.Core.Api/Controllers/BlogController.cs
@@ -83,7 +83,7 @@ public async Task>> Get(int id, int page = 1
[HttpGet("{id}")]
//[Authorize(Policy = "Scope_BlogModule_Policy")]
[Authorize]
- public async Task> Get(int id)
+ public async Task> Get(long id)
{
return Success(await _blogArticleServices.GetBlogDetails(id));
}
@@ -96,7 +96,7 @@ public async Task> Get(int id)
///
[HttpGet]
[Route("DetailNuxtNoPer")]
- public async Task> DetailNuxtNoPer(int id)
+ public async Task> DetailNuxtNoPer(long id)
{
_logger.LogInformation("xxxxxxxxxxxxxxxxxxx");
return Success(await _blogArticleServices.GetBlogDetails(id));
@@ -104,7 +104,7 @@ public async Task> DetailNuxtNoPer(int id)
[HttpGet]
[Route("GoUrl")]
- public async Task GoUrl(int id = 0)
+ public async Task GoUrl(long id = 0)
{
var response = await _blogArticleServices.QueryById(id);
if (response != null && response.bsubmitter.IsNotEmptyOrNull())
@@ -136,7 +136,7 @@ public async Task>> GetBlogsByTypesForMVP(string
[HttpGet]
[Route("GetBlogByIdForMVP")]
- public async Task> GetBlogByIdForMVP(int id = 0)
+ public async Task> GetBlogByIdForMVP(long id = 0)
{
if (id > 0)
{
@@ -247,7 +247,7 @@ public async Task> Put([FromBody] BlogArticle BlogArticle)
[HttpDelete]
[Authorize(Permissions.Name)]
[Route("Delete")]
- public async Task> Delete(int id)
+ public async Task> Delete(long id)
{
if (id > 0)
{
diff --git a/Blog.Core.Api/Controllers/DepartmentController.cs b/Blog.Core.Api/Controllers/DepartmentController.cs
index b8174e90..faf1f850 100644
--- a/Blog.Core.Api/Controllers/DepartmentController.cs
+++ b/Blog.Core.Api/Controllers/DepartmentController.cs
@@ -109,7 +109,7 @@ public async Task>> GetTreeTable(long f = 0, strin
///
///
[HttpGet]
- public async Task> GetDepartmentTree(int pid = 0)
+ public async Task> GetDepartmentTree(long pid = 0)
{
var departments = await _departmentServices.Query(d => d.IsDeleted == false);
var departmentTrees = (from child in departments
@@ -168,7 +168,7 @@ public async Task> Put([FromBody] Department request)
}
[HttpDelete]
- public async Task> Delete(int id)
+ public async Task> Delete(long id)
{
var data = new MessageModel();
var model = await _departmentServices.QueryById(id);
diff --git a/Blog.Core.Api/Controllers/ModuleController.cs b/Blog.Core.Api/Controllers/ModuleController.cs
index 2da284ba..27e6f4db 100644
--- a/Blog.Core.Api/Controllers/ModuleController.cs
+++ b/Blog.Core.Api/Controllers/ModuleController.cs
@@ -119,7 +119,7 @@ public async Task> Put([FromBody] Modules module)
///
// DELETE: api/ApiWithActions/5
[HttpDelete]
- public async Task> Delete(int id)
+ public async Task> Delete(long id)
{
if (id <= 0)
return Failed("缺少参数");
diff --git a/Blog.Core.Api/Controllers/PermissionController.cs b/Blog.Core.Api/Controllers/PermissionController.cs
index 059e9b18..7346cc21 100644
--- a/Blog.Core.Api/Controllers/PermissionController.cs
+++ b/Blog.Core.Api/Controllers/PermissionController.cs
@@ -79,21 +79,6 @@ public async Task>> Get(int page = 1, string
key = "";
}
- #region 舍弃
- //var permissions = await _permissionServices.Query(a => a.IsDeleted != true);
- //if (!string.IsNullOrEmpty(key))
- //{
- // permissions = permissions.Where(t => (t.Name != null && t.Name.Contains(key))).ToList();
- //}
- ////筛选后的数据总数
- //totalCount = permissions.Count;
- ////筛选后的总页数
- //pageCount = (Math.Ceiling(totalCount.ObjToDecimal() / intTotalCount.ObjToDecimal())).ObjToInt();
- //permissions = permissions.OrderByDescending(d => d.Id).Skip((page - 1) * intTotalCount).Take(intTotalCount).ToList();
- #endregion
-
-
-
permissions = await _permissionServices.QueryPage(a => a.IsDeleted != true && (a.Name != null && a.Name.Contains(key)), page, pageSize, " Id desc ");
@@ -162,7 +147,7 @@ public async Task>> Get(int page = 1, string
///
[HttpGet]
[AllowAnonymous]
- public async Task>> GetTreeTable(int f = 0, string key = "")
+ public async Task>> GetTreeTable(long f = 0, string key = "")
{
List permissions = new List();
var apiList = await _moduleServices.Query(d => d.IsDeleted == false);
@@ -245,7 +230,7 @@ public async Task> Post([FromBody] Permission permission)
///
[HttpPost]
public async Task> Assign([FromBody] AssignView assignView)
- {
+ {
if (assignView.rid > 0)
{
//开启事务
@@ -258,7 +243,7 @@ public async Task> Assign([FromBody] AssignView assignView)
var permissions = await _permissionServices.Query(d => d.IsDeleted == false);
List new_rmps = new List();
- var nowTime = _permissionServices.Db.GetDate();
+ var nowTime = _permissionServices.Db.GetDate();
foreach (var item in assignView.pids)
{
var moduleid = permissions.Find(p => p.Id == item)?.Mid;
@@ -268,7 +253,7 @@ public async Task> Assign([FromBody] AssignView assignView)
{
IsDeleted = false,
RoleId = assignView.rid,
- ModuleId = moduleid.ObjToInt(),
+ ModuleId = moduleid.ObjToLong(),
PermissionId = item,
CreateId = find_old_rmps == null ? _user.ID : find_old_rmps.CreateId,
CreateBy = find_old_rmps == null ? _user.Name : find_old_rmps.CreateBy,
@@ -280,7 +265,7 @@ public async Task> Assign([FromBody] AssignView assignView)
};
new_rmps.Add(roleModulePermission);
}
- if(new_rmps.Count>0) await _roleModulePermissionServices.Add(new_rmps);
+ if (new_rmps.Count > 0) await _roleModulePermissionServices.Add(new_rmps);
_unitOfWorkManage.CommitTran();
}
catch (Exception)
@@ -294,7 +279,7 @@ public async Task> Assign([FromBody] AssignView assignView)
else
{
return Failed("请选择要操作的角色");
- }
+ }
}
@@ -305,7 +290,7 @@ public async Task> Assign([FromBody] AssignView assignView)
///
///
[HttpGet]
- public async Task> GetPermissionTree(int pid = 0, bool needbtn = false)
+ public async Task> GetPermissionTree(long pid = 0, bool needbtn = false)
{
//var data = new MessageModel();
@@ -355,7 +340,7 @@ public async Task> GetNavigationBar(long uid)
var data = new MessageModel();
- var uidInHttpcontext1 = 0;
+ long uidInHttpcontext1 = 0;
var roleIds = new List();
// ids4和jwt切换
if (Permissions.IsUseIds4)
@@ -363,7 +348,7 @@ public async Task> GetNavigationBar(long uid)
// ids4
uidInHttpcontext1 = (from item in _httpContext.HttpContext.User.Claims
where item.Type == "sub"
- select item.Value).FirstOrDefault().ObjToInt();
+ select item.Value).FirstOrDefault().ObjToLong();
roleIds = (from item in _httpContext.HttpContext.User.Claims
where item.Type == "role"
select item.Value.ObjToLong()).ToList();
@@ -371,7 +356,7 @@ public async Task> GetNavigationBar(long uid)
else
{
// jwt
- uidInHttpcontext1 = ((JwtHelper.SerializeJwt(_httpContext.HttpContext.Request.Headers["Authorization"].ObjToString().Replace("Bearer ", "")))?.Uid).ObjToInt();
+ uidInHttpcontext1 = ((JwtHelper.SerializeJwt(_httpContext.HttpContext.Request.Headers["Authorization"].ObjToString().Replace("Bearer ", "")))?.Uid).ObjToLong();
roleIds = (await _userRoleServices.Query(d => d.IsDeleted == false && d.UserId == uid)).Select(d => d.RoleId.ObjToLong()).Distinct().ToList();
}
@@ -446,7 +431,7 @@ public async Task>> GetNavigationBarPro(long
{
var data = new MessageModel>();
- var uidInHttpcontext1 = 0;
+ long uidInHttpcontext1 = 0;
var roleIds = new List();
// ids4和jwt切换
if (Permissions.IsUseIds4)
@@ -454,7 +439,7 @@ public async Task>> GetNavigationBarPro(long
// ids4
uidInHttpcontext1 = (from item in _httpContext.HttpContext.User.Claims
where item.Type == "sub"
- select item.Value).FirstOrDefault().ObjToInt();
+ select item.Value).FirstOrDefault().ObjToLong();
roleIds = (from item in _httpContext.HttpContext.User.Claims
where item.Type == "role"
select item.Value.ObjToLong()).ToList();
@@ -462,7 +447,7 @@ public async Task>> GetNavigationBarPro(long
else
{
// jwt
- uidInHttpcontext1 = ((JwtHelper.SerializeJwt(_httpContext.HttpContext.Request.Headers["Authorization"].ObjToString().Replace("Bearer ", "")))?.Uid).ObjToInt();
+ uidInHttpcontext1 = ((JwtHelper.SerializeJwt(_httpContext.HttpContext.Request.Headers["Authorization"].ObjToString().Replace("Bearer ", "")))?.Uid).ObjToLong();
roleIds = (await _userRoleServices.Query(d => d.IsDeleted == false && d.UserId == uid)).Select(d => d.RoleId.ObjToLong()).Distinct().ToList();
}
@@ -519,14 +504,14 @@ orderby item.Id
///
[HttpGet]
[AllowAnonymous]
- public async Task> GetPermissionIdByRoleId(int rid = 0)
+ public async Task> GetPermissionIdByRoleId(long rid = 0)
{
//var data = new MessageModel();
var rmps = await _roleModulePermissionServices.Query(d => d.IsDeleted == false && d.RoleId == rid);
var permissionTrees = (from child in rmps
orderby child.Id
- select child.PermissionId.ObjToInt()).ToList();
+ select child.PermissionId.ObjToLong()).ToList();
var permissions = await _permissionServices.Query(d => d.IsDeleted == false);
List assignbtns = new List();
@@ -592,7 +577,7 @@ public async Task> Put([FromBody] Permission permission)
///
// DELETE: api/ApiWithActions/5
[HttpDelete]
- public async Task> Delete(int id)
+ public async Task> Delete(long id)
{
var data = new MessageModel();
if (id > 0)
@@ -654,7 +639,7 @@ public async Task> BatchPost([FromBody] List pe
/// 是否执行迁移到数据
///
[HttpGet]
- public async Task>> MigratePermission(string action = "", string controllerName = "", int pid = 0, bool isAction = false)
+ public async Task>> MigratePermission(string action = "", string controllerName = "", long pid = 0, bool isAction = false)
{
var data = new MessageModel>();
if (controllerName.IsNullOrEmpty())
@@ -776,12 +761,12 @@ public async Task>> MigratePermission(string actio
public class AssignView
{
- public List pids { get; set; }
- public int rid { get; set; }
+ public List pids { get; set; }
+ public long rid { get; set; }
}
public class AssignShow
{
- public List permissionids { get; set; }
+ public List permissionids { get; set; }
public List assignbtns { get; set; }
}
diff --git a/Blog.Core.Api/Controllers/RoleController.cs b/Blog.Core.Api/Controllers/RoleController.cs
index c96502c8..0b93e943 100644
--- a/Blog.Core.Api/Controllers/RoleController.cs
+++ b/Blog.Core.Api/Controllers/RoleController.cs
@@ -112,7 +112,7 @@ public async Task> Put([FromBody] Role role)
///
// DELETE: api/ApiWithActions/5
[HttpDelete]
- public async Task> Delete(int id)
+ public async Task> Delete(long id)
{
var data = new MessageModel();
diff --git a/Blog.Core.Api/Controllers/TasksQzController.cs b/Blog.Core.Api/Controllers/TasksQzController.cs
index ca9d37bc..887cfcfc 100644
--- a/Blog.Core.Api/Controllers/TasksQzController.cs
+++ b/Blog.Core.Api/Controllers/TasksQzController.cs
@@ -172,7 +172,7 @@ public async Task> Put([FromBody] TasksQz tasksQz)
///
///
[HttpDelete]
- public async Task> Delete(int jobId)
+ public async Task> Delete(long jobId)
{
var data = new MessageModel();
@@ -221,7 +221,7 @@ public async Task> Delete(int jobId)
///
///
[HttpGet]
- public async Task> StartJob(int jobId)
+ public async Task> StartJob(long jobId)
{
var data = new MessageModel();
@@ -278,7 +278,7 @@ public async Task> StartJob(int jobId)
///
///
[HttpGet]
- public async Task> StopJob(int jobId)
+ public async Task> StopJob(long jobId)
{
var data = new MessageModel();
@@ -318,7 +318,7 @@ public async Task> StopJob(int jobId)
///
///
[HttpGet]
- public async Task> PauseJob(int jobId)
+ public async Task> PauseJob(long jobId)
{
var data = new MessageModel();
var model = await _tasksQzServices.QueryById(jobId);
@@ -372,7 +372,7 @@ public async Task> PauseJob(int jobId)
///
///
[HttpGet]
- public async Task> ResumeJob(int jobId)
+ public async Task> ResumeJob(long jobId)
{
var data = new MessageModel();
@@ -428,7 +428,7 @@ public async Task> ResumeJob(int jobId)
///
///
[HttpGet]
- public async Task> ReCovery(int jobId)
+ public async Task> ReCovery(long jobId)
{
var data = new MessageModel();
var model = await _tasksQzServices.QueryById(jobId);
@@ -507,7 +507,7 @@ public MessageModel> GetTaskNameSpace()
///
///
[HttpGet]
- public async Task> ExecuteJob(int jobId)
+ public async Task> ExecuteJob(long jobId)
{
var data = new MessageModel();
@@ -527,7 +527,7 @@ public async Task> ExecuteJob(int jobId)
///
///
[HttpGet]
- public async Task>> GetTaskLogs(int jobId, int page = 1, int pageSize = 10, DateTime? runTimeStart = null, DateTime? runTimeEnd = null)
+ public async Task>> GetTaskLogs(long jobId, int page = 1, int pageSize = 10, DateTime? runTimeStart = null, DateTime? runTimeEnd = null)
{
var model = await _tasksLogServices.GetTaskLogs(jobId, page, pageSize, runTimeStart, runTimeEnd);
return MessageModel>.Message(model.dataCount >= 0, "获取成功", model);
@@ -537,7 +537,7 @@ public async Task>> GetTaskLogs(int jobId, int
///
///
[HttpGet]
- public async Task> GetTaskOverview(int jobId, int page = 1, int pageSize = 10, DateTime? runTimeStart = null, DateTime? runTimeEnd = null, string type = "month")
+ public async Task> GetTaskOverview(long jobId, int page = 1, int pageSize = 10, DateTime? runTimeStart = null, DateTime? runTimeEnd = null, string type = "month")
{
var model = await _tasksLogServices.GetTaskOverview(jobId, runTimeStart, runTimeEnd, type);
return MessageModel.Message(true, "获取成功", model);
diff --git a/Blog.Core.Api/Controllers/TopicController.cs b/Blog.Core.Api/Controllers/TopicController.cs
index 308ad082..253f54ff 100644
--- a/Blog.Core.Api/Controllers/TopicController.cs
+++ b/Blog.Core.Api/Controllers/TopicController.cs
@@ -44,7 +44,7 @@ public async Task>> Get()
// GET: api/Topic/5
[HttpGet("{id}")]
- public string Get(int id)
+ public string Get(long id)
{
return "value";
}
@@ -57,13 +57,13 @@ public void Post([FromBody] string value)
// PUT: api/Topic/5
[HttpPut("{id}")]
- public void Put(int id, [FromBody] string value)
+ public void Put(long id, [FromBody] string value)
{
}
// DELETE: api/ApiWithActions/5
[HttpDelete("{id}")]
- public void Delete(int id)
+ public void Delete(long id)
{
}
}
diff --git a/Blog.Core.Api/Controllers/TopicDetailController.cs b/Blog.Core.Api/Controllers/TopicDetailController.cs
index 55af1a75..374aca24 100644
--- a/Blog.Core.Api/Controllers/TopicDetailController.cs
+++ b/Blog.Core.Api/Controllers/TopicDetailController.cs
@@ -42,7 +42,7 @@ public TopicDetailController(ITopicServices topicServices, ITopicDetailServices
[AllowAnonymous]
public async Task>> Get(int page = 1, string tname = "", string key = "", int intPageSize = 12)
{
- int tid = 0;
+ long tid = 0;
if (string.IsNullOrEmpty(key) || string.IsNullOrWhiteSpace(key))
{
@@ -56,7 +56,7 @@ public async Task>> Get(int page = 1, string
if (!string.IsNullOrEmpty(tname))
{
- tid = ((await _topicServices.Query(ts => ts.tName == tname)).FirstOrDefault()?.Id).ObjToInt();
+ tid = ((await _topicServices.Query(ts => ts.tName == tname)).FirstOrDefault()?.Id).ObjToLong();
}
@@ -81,7 +81,7 @@ public async Task>> Get(int page = 1, string
// GET: api/TopicDetail/5
[HttpGet("{id}")]
[AllowAnonymous]
- public async Task> Get(int id)
+ public async Task> Get(long id)
{
var data = new MessageModel();
var response = id > 0 ? await _topicDetailServices.QueryById(id) : new TopicDetail();
@@ -154,7 +154,7 @@ public async Task> Update([FromBody] TopicDetail topicDetai
///
// DELETE: api/ApiWithActions/5
[HttpDelete]
- public async Task> Delete(int id)
+ public async Task> Delete(long id)
{
var data = new MessageModel();
if (id > 0)
diff --git a/Blog.Core.Api/Controllers/TransactionController.cs b/Blog.Core.Api/Controllers/TransactionController.cs
index 67ab576e..9853d985 100644
--- a/Blog.Core.Api/Controllers/TransactionController.cs
+++ b/Blog.Core.Api/Controllers/TransactionController.cs
@@ -95,7 +95,7 @@ public async Task>> Get()
// GET: api/Transaction/5
[HttpGet("{id}")]
- public async Task> Get(int id)
+ public async Task> Get(long id)
{
return await _guestbookServices.TestTranInRepository();
}
@@ -126,7 +126,7 @@ public void Post([FromBody] string value)
// PUT: api/Transaction/5
[HttpPut("{id}")]
- public void Put(int id, [FromBody] string value)
+ public void Put(long id, [FromBody] string value)
{
}
@@ -136,7 +136,7 @@ public void Put(int id, [FromBody] string value)
///
///
[HttpDelete("{id}")]
- public async Task Delete(int id)
+ public async Task Delete(long id)
{
return await _guestbookServices.TestTranInRepositoryAOP();
}
diff --git a/Blog.Core.Api/Controllers/UserController.cs b/Blog.Core.Api/Controllers/UserController.cs
index 27989821..95137c8e 100644
--- a/Blog.Core.Api/Controllers/UserController.cs
+++ b/Blog.Core.Api/Controllers/UserController.cs
@@ -103,7 +103,7 @@ public async Task>> Get(int page = 1, str
return Success(data.ConvertTo(_mapper));
}
- private (string, List) GetFullDepartmentName(List departments, int departmentId)
+ private (string, List) GetFullDepartmentName(List departments, long departmentId)
{
var departmentModel = departments.FirstOrDefault(d => d.Id == departmentId);
if (departmentModel == null)
@@ -265,7 +265,7 @@ public async Task> Put([FromBody] SysUserInfoDto sysUserInf
///
// DELETE: api/ApiWithActions/5
[HttpDelete]
- public async Task> Delete(int id)
+ public async Task> Delete(long id)
{
var data = new MessageModel();
if (id > 0)
diff --git a/Blog.Core.Api/Controllers/UserRoleController.cs b/Blog.Core.Api/Controllers/UserRoleController.cs
index c21ec6f4..693a68b8 100644
--- a/Blog.Core.Api/Controllers/UserRoleController.cs
+++ b/Blog.Core.Api/Controllers/UserRoleController.cs
@@ -80,7 +80,7 @@ public async Task> AddRole(string roleName)
///
///
[HttpGet]
- public async Task> AddUserRole(int uid, int rid)
+ public async Task> AddUserRole(long uid, long rid)
{
return new MessageModel()
{
diff --git a/Blog.Core.Common/Helper/RecursionHelper.cs b/Blog.Core.Common/Helper/RecursionHelper.cs
index f6f21a38..092a0678 100644
--- a/Blog.Core.Common/Helper/RecursionHelper.cs
+++ b/Blog.Core.Common/Helper/RecursionHelper.cs
@@ -8,7 +8,7 @@ namespace Blog.Core.Common.Helper
///
public static class RecursionHelper
{
- public static void LoopToAppendChildren(List all, PermissionTree curItem, int pid, bool needbtn)
+ public static void LoopToAppendChildren(List all, PermissionTree curItem, long pid, bool needbtn)
{
var subItems = all.Where(ee => ee.Pid == curItem.value).ToList();
@@ -52,7 +52,7 @@ public static void LoopToAppendChildren(List all, PermissionTree
LoopToAppendChildren(all, subItem, pid, needbtn);
}
}
- public static void LoopToAppendChildren(List all, DepartmentTree curItem, int pid)
+ public static void LoopToAppendChildren(List all, DepartmentTree curItem, long pid)
{
var subItems = all.Where(ee => ee.Pid == curItem.value).ToList();
diff --git a/Blog.Core.IServices/IBlogArticleServices.cs b/Blog.Core.IServices/IBlogArticleServices.cs
index 23e6081b..a38826fb 100644
--- a/Blog.Core.IServices/IBlogArticleServices.cs
+++ b/Blog.Core.IServices/IBlogArticleServices.cs
@@ -9,7 +9,7 @@ namespace Blog.Core.IServices
public interface IBlogArticleServices :IBaseServices
{
Task> GetBlogs();
- Task GetBlogDetails(int id);
+ Task GetBlogDetails(long id);
}
diff --git a/Blog.Core.IServices/ITasksLogServices.cs b/Blog.Core.IServices/ITasksLogServices.cs
index fb15c8dd..fb6ad8a7 100644
--- a/Blog.Core.IServices/ITasksLogServices.cs
+++ b/Blog.Core.IServices/ITasksLogServices.cs
@@ -12,8 +12,8 @@ namespace Blog.Core.IServices
///
public interface ITasksLogServices :IBaseServices
{
- public Task> GetTaskLogs(int jobId, int page, int intPageSize,DateTime? runTime,DateTime? endTime);
- public Task GetTaskOverview(int jobId, DateTime? runTime, DateTime? endTime, string type);
+ public Task> GetTaskLogs(long jobId, int page, int intPageSize,DateTime? runTime,DateTime? endTime);
+ public Task GetTaskOverview(long jobId, DateTime? runTime, DateTime? endTime, string type);
}
}
\ No newline at end of file
diff --git a/Blog.Core.IServices/IUserRoleServices.cs b/Blog.Core.IServices/IUserRoleServices.cs
index 9e7d3d29..91272a09 100644
--- a/Blog.Core.IServices/IUserRoleServices.cs
+++ b/Blog.Core.IServices/IUserRoleServices.cs
@@ -10,8 +10,8 @@ namespace Blog.Core.IServices
public interface IUserRoleServices :IBaseServices
{
- Task SaveUserRole(int uid, int rid);
- Task GetRoleIdByUid(int uid);
+ Task SaveUserRole(long uid, long rid);
+ Task GetRoleIdByUid(long uid);
}
}
diff --git a/Blog.Core.Model/ViewModels/BlogViewModels.cs b/Blog.Core.Model/ViewModels/BlogViewModels.cs
index 411a8ef7..86c16618 100644
--- a/Blog.Core.Model/ViewModels/BlogViewModels.cs
+++ b/Blog.Core.Model/ViewModels/BlogViewModels.cs
@@ -10,7 +10,7 @@ public class BlogViewModels
///
///
///
- public int bID { get; set; }
+ public long bID { get; set; }
/// 创建人
///
///
diff --git a/Blog.Core.Model/ViewModels/SysUserInfoDto.cs b/Blog.Core.Model/ViewModels/SysUserInfoDto.cs
index 33d84161..3b5451f0 100644
--- a/Blog.Core.Model/ViewModels/SysUserInfoDto.cs
+++ b/Blog.Core.Model/ViewModels/SysUserInfoDto.cs
@@ -3,13 +3,13 @@
namespace Blog.Core.Model.ViewModels
{
- public class SysUserInfoDto : SysUserInfoDtoRoot
+ public class SysUserInfoDto : SysUserInfoDtoRoot
{
public string uLoginName { get; set; }
public string uLoginPWD { get; set; }
public string uRealName { get; set; }
public int uStatus { get; set; }
- public int DepartmentId { get; set; }
+ public long DepartmentId { get; set; }
public string uRemark { get; set; }
public System.DateTime uCreateTime { get; set; } = DateTime.Now;
public System.DateTime uUpdateTime { get; set; } = DateTime.Now;
@@ -22,7 +22,7 @@ public class SysUserInfoDto : SysUserInfoDtoRoot
public string addr { get; set; }
public bool tdIsDelete { get; set; }
public List RoleNames { get; set; }
- public List Dids { get; set; }
+ public List Dids { get; set; }
public string DepartmentName { get; set; }
}
}
diff --git a/Blog.Core.Services/BlogArticleServices.cs b/Blog.Core.Services/BlogArticleServices.cs
index eeff04e3..67ea2b9e 100644
--- a/Blog.Core.Services/BlogArticleServices.cs
+++ b/Blog.Core.Services/BlogArticleServices.cs
@@ -23,7 +23,7 @@ public BlogArticleServices(IMapper mapper)
///
///
///
- public async Task GetBlogDetails(int id)
+ public async Task GetBlogDetails(long id)
{
// 此处想获取上一条下一条数据,因此将全部数据list出来,有好的想法请提出
//var bloglist = await base.Query(a => a.IsDeleted==false, a => a.bID);
diff --git a/Blog.Core.Services/TasksLogServices.cs b/Blog.Core.Services/TasksLogServices.cs
index 49393cd4..07d95f1f 100644
--- a/Blog.Core.Services/TasksLogServices.cs
+++ b/Blog.Core.Services/TasksLogServices.cs
@@ -14,7 +14,7 @@ namespace Blog.Core.Services
{
public partial class TasksLogServices : BaseServices, ITasksLogServices
{
- public async Task> GetTaskLogs(int jobId, int page, int intPageSize, DateTime? runTime, DateTime? endTime)
+ public async Task> GetTaskLogs(long jobId, int page, int intPageSize, DateTime? runTime, DateTime? endTime)
{
RefAsync totalCount = 0;
Expression> whereExpression = log => true;
@@ -41,7 +41,7 @@ public async Task> GetTaskLogs(int jobId, int page, int intP
.ToPageListAsync(page, intPageSize, totalCount);
return new PageModel(page, totalCount, intPageSize, data);
}
- public async Task GetTaskOverview(int jobId, DateTime? runTime, DateTime? endTime, string type)
+ public async Task GetTaskOverview(long jobId, DateTime? runTime, DateTime? endTime, string type)
{
//按年
if ("year".Equals(type))
diff --git a/Blog.Core.Services/UserRoleServices.cs b/Blog.Core.Services/UserRoleServices.cs
index 38f524da..26194837 100644
--- a/Blog.Core.Services/UserRoleServices.cs
+++ b/Blog.Core.Services/UserRoleServices.cs
@@ -19,7 +19,7 @@ public class UserRoleServices : BaseServices, IUserRoleServices
///
///
///
- public async Task SaveUserRole(int uid, int rid)
+ public async Task SaveUserRole(long uid, long rid)
{
UserRole userRole = new UserRole(uid, rid);
@@ -42,7 +42,7 @@ public async Task SaveUserRole(int uid, int rid)
[Caching(AbsoluteExpiration = 30)]
- public async Task GetRoleIdByUid(int uid)
+ public async Task GetRoleIdByUid(long uid)
{
return ((await base.Query(d => d.UserId == uid)).OrderByDescending(d => d.Id).LastOrDefault()?.RoleId).ObjToInt();
}
diff --git a/Blog.Core.Tests/Controller_Test/BlogController_Should.cs b/Blog.Core.Tests/Controller_Test/BlogController_Should.cs
index 3d1e3178..59d42ae0 100644
--- a/Blog.Core.Tests/Controller_Test/BlogController_Should.cs
+++ b/Blog.Core.Tests/Controller_Test/BlogController_Should.cs
@@ -53,7 +53,7 @@ public async void Get_Blog_Page_Test()
[Fact]
public async void Get_Blog_Test()
{
- MessageModel blogVo = await blogController.Get(1);
+ MessageModel blogVo = await blogController.Get(1.ObjToLong());
Assert.NotNull(blogVo);
}
From 5e84e11ca84f3bf245ef4307e17b48cd2c20b265 Mon Sep 17 00:00:00 2001
From: LemonNoCry <773596523@qq.com>
Date: Sun, 2 Apr 2023 15:56:20 +0800
Subject: [PATCH 14/84] =?UTF-8?q?=E2=9C=A8=20=E8=B0=83=E6=95=B4?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.gitignore | 1 +
Blog.Core.Api/Blog.Core.Api.csproj | 1 +
Blog.Core.Model/Models/PasswordLib.cs | 2 +-
Blog.Core.Tests/WMBlog.db | Bin 200704 -> 0 bytes
4 files changed, 3 insertions(+), 1 deletion(-)
delete mode 100644 Blog.Core.Tests/WMBlog.db
diff --git a/.gitignore b/.gitignore
index 4f554bea..fa4a3448 100644
--- a/.gitignore
+++ b/.gitignore
@@ -358,3 +358,4 @@ Blog.Core.Api/wwwroot/ui/
*.db
/Blog.Core.Api/WMBlog.db-journal
Logs
+*.db
diff --git a/Blog.Core.Api/Blog.Core.Api.csproj b/Blog.Core.Api/Blog.Core.Api.csproj
index 3bf64399..0d32998e 100644
--- a/Blog.Core.Api/Blog.Core.Api.csproj
+++ b/Blog.Core.Api/Blog.Core.Api.csproj
@@ -52,6 +52,7 @@
+
diff --git a/Blog.Core.Model/Models/PasswordLib.cs b/Blog.Core.Model/Models/PasswordLib.cs
index 2b43c265..9eb9292f 100644
--- a/Blog.Core.Model/Models/PasswordLib.cs
+++ b/Blog.Core.Model/Models/PasswordLib.cs
@@ -7,7 +7,7 @@ namespace Blog.Core.Model.Models
/// 密码库表
///
[SugarTable("PasswordLib", "密码库表")]//('数据库表名','数据库表备注')
- [TenantAttribute("WMBLOG_MYSQL_2")] //('代表是哪个数据库,名字是appsettings.json 的 ConnId')
+ //[TenantAttribute("WMBLOG_MYSQL_2")] //('代表是哪个数据库,名字是appsettings.json 的 ConnId')
public class PasswordLib
{
[SugarColumn(IsNullable = false, IsPrimaryKey = true, IsIdentity = true)]
diff --git a/Blog.Core.Tests/WMBlog.db b/Blog.Core.Tests/WMBlog.db
deleted file mode 100644
index 4931b9674dbdfa61661ba06a34e3c55254029529..0000000000000000000000000000000000000000
GIT binary patch
literal 0
HcmV?d00001
literal 200704
zcmeIbc~o0hnlCDW&;ST|h%Jvn#&K+dF-Xita*D|g6%QEWOqIkX;22aEk|GHYsjez8
z1_L(6PCO6s5Mw*B4UXdk4A{K)x>mog*WK&Z>Z-S@*Q#D`z1O94ByM+Cs{iP^w^!ZQ
z^}c~*?ZtX@N&Y@SRmmwm@z
zkjZ2j@P8xxKlE7wUlgGq@LxISd#tY+vJLBNlHhKl?%z2BO=tLJ=8uBfdltE)29m6dO;
zGGuV>WUSLBXVh%1uFNpl9A2u4avQeqs55Ney>+XhrnY)pS?$|~*Q?$(lRxBc&CTT9t$7o$LU)bA
zyJZax&Q^zayS0Uiq>9q9%WL(vdN?K{bA#wrZnx82fs}~fe+}|ka{$Z^*$|~2rTCzg
z@_21d#}vsb+?3Tz)!C4xjquG2-*`FQ?LwEQNU+uF@q)QAQ+UA!Q3DK_9cgNne$^^@
zXA|r89WKfZSX-SUse{wPzdUXbsj?Jn1S2sy9Q`81EJ?;XIFrD;j*S{7{5Z
zKH<~U4iEyiy@$kA<9l4yg3RCqF(bLg>ZTmtXx)a)!|y3o`t)>pr-lvEEvS;KcRKfl
zzo__u8ooZmP_4H+n|OBc=xtytP*g{9D^OmNRw!`}VOzk94p+0&!3iCx%z3wW?u32No-No=j$g=^(X%4KzXTfiBSZ%RJHksC9l7?qq_
z%5Fs!pQo8;bU^{MygWMjHH0ZT!B)x&g^iPOHc2?>r!9)1hMDaW@SuhL1>Vi*!h~%L
z13yz~;+7bJ{B$M8Ce|84t=_Ro!S=4YD%b*34)I*(_Szck6z6La-=&;8tWWFX?_AY;
zTI*YEUN6@bh5W#-_u9O6Zr~Rba{F2J4N$C_obD+CydElKFT^It+k(PV?{!=E?zJ_D
z^c2{N7c{h>=-%Gi5;KW-Cy3|$dU5aa)6`NeR`sv)x`
zL8;HmlE2MT;`zW19a4^6NtmycJLDizg@JFkIKdBlm
z{Dnb3`49#O1B3y>0AYYIKo}ql5C#YXgaN_;VSq63XUqT^|EK8Qmg#<{`;G1wx}WI=
zbvJdVbzQnvoeeIN4`F~XKo}ql5C#YXgaN_;VSq3|7$6J~1_%RFF_4y$xJn+G|D;Jy
zPF$|3vwHSy&wuVZ|Yqiy)-GYAOWR;89y)qvxaiFz+^3$8zpN~D-svU(XEwfiGUorbtokvak(4|c($a;
zK{sa(4|)GTl@rN5!T@1_FhCd}3=jqg1B3y>0AYYIKo}ql{CO~d#{cq^@50AYYIKo}ql5C#YX&&)tio;*#aKU}h=zf`Wt%af_CjV(3@^VPAy&>7~;1Ez2A
zoAHa))w>K1>VU!8*l0LF)qBw1Ti=Wy_c&p5oda&CqiJJZGi7k2)yf{&eaPUlHc^HK
ztHa^+8tN&7m0fEL*XyYUE9@R&@Up34e+0M&3*PtInp$C}9C#s!_Uy5uZN1netQwmK
zw#3Lf0nzP8a-z
zEvtt2zi96@@EIoAwF$qgHK15|ld3mVINcOWziZQWr`HBM7GMwWcI*FiUb8wH
zVHY9;BrzPKyoN^Dy$aqAJE+EB0t|;X)G*{8EY8g>g6$CUg7;t-BM6vHx}m>=jH^{)-)gTKql>m8mqTCcnucXLr`y{yv@$W*m=aM(2MlgX@Zs*
z>fF`_o1@84X>)_wu$P3PV&l6=6z2flMmtWS9D3g6^R&y^>TaMy?kaP54p8pUFC!G^
zy*5W9TkcT#Uh6SfT`qgbYc8kL?g^?ht6QE7Nf{M)bZisp|yh2}pV#+m^Wak>;pCLDQBl}O}
z5*q(&Qs0y5KGtQY{Z-l??SI$yX){v)H@HMTgaN_;VSq3|7$6J~1_%R$0m1-b;Mo~y
zfbGQ=8Rx4t>a0>(sXTXm@%pM=%<-f2(D*mw-A4b|k#EL(C{LiRogTmDzj%cH_#u7&
zmMPa{%FfM40~cfAMq~cQ{GtsoRux<>fFTXKtbSjumCesu7z9!0u76{96=?B2z7}Xd
z?Z0$&e=9W|fXOHVkiQXMwyCtTr6rt97}w{or%#^n-yNbK^s{;BHu<04gsfy|Pk~gh
zv7mUPF;9rZxva1$qoDHE(>;A$DC4t188_yOL4__SQc2*NoTWk5G`Z`I>&q+NsL7@u
zPte1k(A`~=9e42esk4;3(IkeGyD>i><&;v0!}vyenXiU14E{bPOn%8mQ&bQXYz$wf
z62)QYAg}Mxb5rlUq)}_M(lZ0uiv#WitQ&*{d^>
zk}yCRAPf)&2m^!x!T@1_FhCd}3=jqg1K(B#(Aj(my5A%7*P^re(pG67Y2QfwZR*j~
z#zW2sD5s*Y@k0CRDIbED2apvOk7E*o4iz*DEmb9elM
z*O?QybKqJ|L?EY$@}|ObH@g1;(>4Z4{3pBUQ|CqIG~mY_QL`V=<)+n(WST{5g=V3n
z$XGb`%WMF(r(^)q_cDb@Wlb=t!;p=$o^7Bf?oPH{WroM--fPT>0lNQF=1Rxpg_Eo?
zY}#4L_Q6%)4P&;@n81l)y8kTQc?W1`&JEBL=UCirPKOO9#LNn^+W^RGqLAtCYm*ml
z!UQyW@CJ*Cwxq~uWY64_?Bspv$jLdv+=iXZ!7@n)d-0jUjFQ3H6ILQRw+XYhh4R8P
z^+5OM%$4gbop4}YaA%MlxVPQ9-`2!V8Y{QD^-{~w!4=4c5}^&gi7WK|^XOS?XP?l9
zGT5Y~$srk;T8@y@BgkvmN+lS^{9szZ^q;J6Z3;ZPMfVTKS4p%i1DNyzaTw6a=8m&J
z3!+#8+z*zbTybg&oGV-@1a5y6=y}K@!ZCwXjteHsNx-r#L0Fvn4`cZz2AR{3qp(_~
zK-u*Oic|726fXHfC|vTTWNfi$#&Bo|(V&8t0M#yA1Xx)+#N#8-f0^z(!(2NhECT=<
zDV1I~MM*Hh^#aOmRD=dYhP6NlFEMbO3lSoxJ?90EIHIKRaW6oCoLYt#KB9nrc1egPv3j92(2Ejj+1b{QQwmTUD52imtA;EYanDc#qY@aBpiv2q4VPR`=cH6IPn#_6rcY05{eTg2j;bK0PwZ=)W0JK^=qQk!%`kt
zCB)HK$rnE|36XpZ|HXxn*Xo+H|+tf
zJhd}bo^mE7H~H_9-_!hy<}Wm<>PzZZRHLfbl)q9^N&lYolO&zu6Ge97&l2BF_^$~c
zCMe}Mw??CZnO`tdCAb7YE;rD_w|q};;~C46Ck3lkQZT6>VAMhw
zJR=!TsFw_rv7!}b^c&Zx1u*KI$WePGfrjj94i_k26
z-BMt1xmvb{<0$6pKw#(wOo1wIZSvqBc*>7t%oWQVFiW4sOlL9i#6T1r?9zZ{c01Eb
z%8q|xR0%V`Rw!LCQJ=+IrIxML$isO4@w0)ar!Zbsqs@zd2WK`(K}^~Qll65tU@{^6
zF``;q1BW42QQTs_RnU#$;EXDE9)b!a|V4)R}}4gN|%cx9Or
z=HG{0#-&i)WjH`30IC)^VJ3daXAqa6Oc}&|CLM601Lop~a>xZ_V3E>|PjHZwH8$d(
z((zvK!hC!dFOwgX;er>bTtekfI_i7}OwAX|rKlhA1TzV4RHnILa(>8-+_({Uqd_{N
z&IwcWLpkIkiu!RD0Oz3@`C?fNJ2H3xZ?F=To<*$#X5@#m$PHCdC*lVVn!Ea1u*g%M2_4HrXpYO)kY7o*Aep$u{v74;yV
zoh$)Qk>Z5O_|NV^>42$dD!y0-MN6S{yksj(#b32l*aoU|Hp334Q8(JFqxM0*T2D
zFa>{2EQpF`tJ~|LFFgeuDIjR(eX!%OmfLY)dIvyrxZ_}l-QBYr5T*pMb~#MFUx@mC
z5cSoOHkLVeEnIi8yP^jsF8D@1$6lJe{uP?m%=QkM<2{of4N9;;q52S}IvGe~m
z30I-IN&AKNY0Cebyk7mc%C(BK30D)&K?3q24E)bzpu?+C=~u6oAI+MvH)#E`U
z<*l}Q&e!CM+N!d;Dnnga`PM2!2Io%3I&E@B&DQG53^@A6OEsZ$L3Y#`w(s7$)lgGg
zy{)YFZNuwTZyU;X*X^j@4r;blZLeDoGSwb<^Z+NQG-ep;ZC)&3KsQ`=IKL#ru;1!N
z4evTrZf+*;Zq1v36}oE_-YvtYc5Jt{P?1zoI(B)j-c~pWBy2J=H;B%j;!=T*{t&V+%
z+K)lh07GU+np&k_wMyRE#JYV4ESv@t;53%VHx1wEksGYftAT+qebPK$21M}8cZ16v7zAJ)PXWI{a;|qAEZ?!r0?RMKE{0U0lpTLK3
z+EGk+bm$WICb!Di;cledyPR%rc@70ETjoVwFUViDXB*{c4c1jW=_&`RH$&AJ?-nlM
zJdcMf8ho$(P{e9J;nUO(5CXQnhs0ImdtB9m%-{quBe}-vhAniWbsI7dzo%5`)6?ah
z8a7C`pfl9!oz8vXFDibZhOf^sRMDYlJUe*wHn0^asyew9C@%@>Av%O@0WYv!%}xg=
zbf7Zl-QKw~;vnI@dS@fYeZspoS8Pd}$J6XQAdDucmA5CcwQ?7(l_Og-MZPKd3`cIv
zkYZGFYAHD14k}PjGtcOP0w_j2I{7t(DLTPcIMR$)QL{@V~O$xSm)m6b37_=`^ncHh?uv46`Nqm=b?yx?s
zkH2$O?`f@Xv3cQqx=0Kb@&mgb4nDJU1HYh$dKN)AU4o3T(v-8d_RF!}ivem`TJtK|Jr*i+h)!rWS_V?tQUs6~-4EI#A;+NL1<9
zu9bH*unvU7a()sZ?lwmKCr{Hj6EK7{2-jOC-|AjqeXCY9jcnwgJfp=TXK~?GgE$e
zAEuc-g|iNtp+@LdL7yJFZlPZZJdGLrn=@n@b<8phaC9dga~Ms{~AJTZYUdt~9m-
z-BX0KZT0N)?EJ6}|7X4+d-&=MqeYN2e!co#XZ;qpvz6cY^P&k3p@nKF^`QKxdc9uW
z1*gb@W7thZ*gp#eraE0vfud1%wOAW7Q@X`~DWEGxkkf$9V;V
zZ(hmv;-Vch4TRhtE!(>HB(Xk(hw1DH56+wAe4WSlC+E%#y$Vhh8EA63XH)Q=lL%M`
zUhPwQKhzJ48sP^AOfGmOf|@{HOon?~&(^>Q#~(cMr>Ry^bOfJ%IHR6_@DzzY&f%q)
znh5G3Cji4agpEVRE|=Tf-e&G#BqAX4{DJGTP%(grjXVy6{$ok1N?%YQ?^?u07<$$Y
zUC~x}P8Z&OQtX~_#U@={T#=-eAUx*+z~T8n|YCesg8X=
z;sjorVArvuDMh7Uv`Bu`81@~4ON;i+Z2N*A(R@Ol54u4LwGSR6wX;S9|tRl&j2c+aGmnbE^Z!cHv$#KMbY~qUxz0=sioAejCDw
z@0n?8qnMRzjV)$RW}Eme1KL&a#n>-)+Pyjz86*Tp2Xl6iApQ;v=0H;|_4Y&jaxUoN
zRoLN8-jpeXy)<}8%&W(1TOFv2#(ho3YaPoe=!Z_(iK}unPI