diff --git a/Tiobon.Core.Api/Controllers/CommonController.cs b/Tiobon.Core.Api/Controllers/CommonController.cs
index 68854d54..2370c5e5 100644
--- a/Tiobon.Core.Api/Controllers/CommonController.cs
+++ b/Tiobon.Core.Api/Controllers/CommonController.cs
@@ -71,6 +71,7 @@ public class CommonController : BaseApiController
/// 获取模块信息接口
///
///
+ ///
///
[HttpPost, Route("GetSelect/{type}")]
public async Task> GetSelectAsync(string type, string Keywords)
diff --git a/Tiobon.Core.Api/Controllers/Ghre/Ghre_CourseController.cs b/Tiobon.Core.Api/Controllers/Ghre/Ghre_CourseController.cs
index 9bd90c76..5e248573 100644
--- a/Tiobon.Core.Api/Controllers/Ghre/Ghre_CourseController.cs
+++ b/Tiobon.Core.Api/Controllers/Ghre/Ghre_CourseController.cs
@@ -54,6 +54,7 @@ public class Ghre_CourseController : BaseController
///
+ ///
///
[HttpPost, Route("QuerySelect")]
public async Task> QuerySelectAsync(long? linkId, string KeyWords)
diff --git a/Tiobon.Core.Api/Controllers/Ghre/Ghre_ExamPaperController.cs b/Tiobon.Core.Api/Controllers/Ghre/Ghre_ExamPaperController.cs
index 0c849102..6f8d8205 100644
--- a/Tiobon.Core.Api/Controllers/Ghre/Ghre_ExamPaperController.cs
+++ b/Tiobon.Core.Api/Controllers/Ghre/Ghre_ExamPaperController.cs
@@ -98,6 +98,7 @@ public class Ghre_ExamPaperController : BaseController
///
+ ///
///
[HttpPost, Route("GetSelect")]
public async Task> GetSelectAsync(long? linkId, string KeyWords)
diff --git a/Tiobon.Core.Api/Controllers/Ghre/Ghre_RequestController.cs b/Tiobon.Core.Api/Controllers/Ghre/Ghre_RequestController.cs
index c9fef3d4..87b669b4 100644
--- a/Tiobon.Core.Api/Controllers/Ghre/Ghre_RequestController.cs
+++ b/Tiobon.Core.Api/Controllers/Ghre/Ghre_RequestController.cs
@@ -1,6 +1,4 @@
-using Consul.Filtering;
-
-namespace Tiobon.Core.Api.Controllers;
+namespace Tiobon.Core.Api.Controllers;
///
/// 培训需求(Controller)
diff --git a/Tiobon.Core.Api/Controllers/Ghre/Ghre_StudyRecordController.cs b/Tiobon.Core.Api/Controllers/Ghre/Ghre_StudyRecordController.cs
index 40f133e7..6742362e 100644
--- a/Tiobon.Core.Api/Controllers/Ghre/Ghre_StudyRecordController.cs
+++ b/Tiobon.Core.Api/Controllers/Ghre/Ghre_StudyRecordController.cs
@@ -86,6 +86,7 @@ public class Ghre_StudyRecordController : BaseController
/// 记录学习时长
///
+ ///
///
///
[HttpPost, Route("RecordDuration/{id}")]
diff --git a/Tiobon.Core.Api/GlobalUsings.cs b/Tiobon.Core.Api/GlobalUsings.cs
index 40d06266..4382be0f 100644
--- a/Tiobon.Core.Api/GlobalUsings.cs
+++ b/Tiobon.Core.Api/GlobalUsings.cs
@@ -1,14 +1,12 @@
global using System.Linq.Expressions;
global using System.Text;
global using System.Text.RegularExpressions;
-global using AutoMapper;
global using Microsoft.AspNetCore.Authorization;
global using Microsoft.AspNetCore.Mvc;
global using Newtonsoft.Json;
global using Tiobon.Core.Api.Filter;
global using Tiobon.Core.Common;
global using Tiobon.Core.Common.Helper;
-global using Tiobon.Core.Common.HttpContextUser;
global using Tiobon.Core.Common.LogHelper;
global using Tiobon.Core.Controllers;
global using Tiobon.Core.IServices;
diff --git a/Tiobon.Core.Api/Tiobon.Core.xml b/Tiobon.Core.Api/Tiobon.Core.xml
index 5596c195..e141ede8 100644
--- a/Tiobon.Core.Api/Tiobon.Core.xml
+++ b/Tiobon.Core.Api/Tiobon.Core.xml
@@ -271,6 +271,7 @@
获取模块信息接口
+
@@ -757,6 +758,7 @@
获取通用列表下拉
+
@@ -955,6 +957,7 @@
获取通用列表下拉
+
@@ -1154,6 +1157,7 @@
记录学习时长
+
diff --git a/Tiobon.Core.DataAccess/ContextFactory.cs b/Tiobon.Core.DataAccess/ContextFactory.cs
index 90a13b26..15c4ae35 100644
--- a/Tiobon.Core.DataAccess/ContextFactory.cs
+++ b/Tiobon.Core.DataAccess/ContextFactory.cs
@@ -1,24 +1,23 @@
using Microsoft.EntityFrameworkCore;
using Tiobon.Core.Common.DB;
-namespace Tiobon.Core.DataAccess
+namespace Tiobon.Core.DataAccess;
+
+///
+/// 直接创建 Context
+///
+public class ContextFactory
{
///
- /// 直接创建 Context
+ /// 创建DbContext
///
- public class ContextFactory
+ ///
+ public static DataContext CreateContext()
{
- ///
- /// 创建DbContext
- ///
- ///
- public static DataContext CreateContext()
- {
- var builder = new DbContextOptionsBuilder();
+ var builder = new DbContextOptionsBuilder();
- var mainConnetctDb = BaseDBConfig.MutiConnectionString.allDbs.Find(x => x.ConnId == MainDb.CurrentDbConnId);
- builder.UseSqlServer(mainConnetctDb.Connection);
- return new DataContext(builder.Options);
- }
+ var mainConnetctDb = BaseDBConfig.MutiConnectionString.allDbs.Find(x => x.ConnId == MainDb.CurrentDbConnId);
+ builder.UseSqlServer(mainConnetctDb.Connection);
+ return new DataContext(builder.Options);
}
}
diff --git a/Tiobon.Core.DataAccess/DataContext.cs b/Tiobon.Core.DataAccess/DataContext.cs
index 04c85e99..5d8a0349 100644
--- a/Tiobon.Core.DataAccess/DataContext.cs
+++ b/Tiobon.Core.DataAccess/DataContext.cs
@@ -1,21 +1,20 @@
using Microsoft.EntityFrameworkCore;
using Tiobon.Core.Model.Models;
-namespace Tiobon.Core.DataAccess
+namespace Tiobon.Core.DataAccess;
+
+public class DataContext : DbContext
{
- public class DataContext : DbContext
- {
- //public virtual DbSet Ghra_Grade { get; set; }
- public virtual DbSet Ghre_Attachment { get; set; }
- public virtual DbSet Ghre_ExamRecordDetail { get; set; }
- public virtual DbSet Ghre_ExamRecordAnswer { get; set; }
+ //public virtual DbSet Ghra_Grade { get; set; }
+ public virtual DbSet Ghre_Attachment { get; set; }
+ public virtual DbSet Ghre_ExamRecordDetail { get; set; }
+ public virtual DbSet Ghre_ExamRecordAnswer { get; set; }
- //占位符
+ //占位符
- public DataContext(DbContextOptions options) : base(options)
- {
- }
+ public DataContext(DbContextOptions options) : base(options)
+ {
}
}
diff --git a/Tiobon.Core.DataAccess/Domain/IBaseCRUDVM.cs b/Tiobon.Core.DataAccess/Domain/IBaseCRUDVM.cs
index 1b475da1..b4fde822 100644
--- a/Tiobon.Core.DataAccess/Domain/IBaseCRUDVM.cs
+++ b/Tiobon.Core.DataAccess/Domain/IBaseCRUDVM.cs
@@ -3,31 +3,30 @@ using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading.Tasks;
-namespace Tiobon.Core.Domain
+namespace Tiobon.Core.Domain;
+
+public interface IBaseCRUDVM where TModel : class
{
- public interface IBaseCRUDVM where TModel : class
- {
- IEnumerable Get();
- TModel Get(Expression> express = null);
+ IEnumerable Get();
+ TModel Get(Expression> express = null);
- TModel GetById(object id);
- Task GetByIdAsync(object id);
+ TModel GetById(object id);
+ Task GetByIdAsync(object id);
- void DoAdd(TModel model);
+ void DoAdd(TModel model);
- Task DoAddAsync(TModel model);
+ Task DoAddAsync(TModel model);
- void DoDelete(object id);
+ void DoDelete(object id);
- Task DoDeleteAsync(Guid id, Guid? updateById = null);
+ Task DoDeleteAsync(Guid id, Guid? updateById = null);
- void DoRealDelete(object id);
+ void DoRealDelete(object id);
- Task DoRealDeleteAsync(object id);
+ Task DoRealDeleteAsync(object id);
- void DoUpdate(TModel model);
+ void DoUpdate(TModel model);
- Task DoUpdateAsync(TModel model);
- Task GetAsync(Expression> express);
- }
+ Task DoUpdateAsync(TModel model);
+ Task GetAsync(Expression> express);
}
diff --git a/Tiobon.Core.DataAccess/Domain/Repositories/BaseCRUDVM.cs b/Tiobon.Core.DataAccess/Domain/Repositories/BaseCRUDVM.cs
index 2b450b78..fcec233a 100644
--- a/Tiobon.Core.DataAccess/Domain/Repositories/BaseCRUDVM.cs
+++ b/Tiobon.Core.DataAccess/Domain/Repositories/BaseCRUDVM.cs
@@ -6,103 +6,102 @@ using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
-namespace Tiobon.Core.Domain
+namespace Tiobon.Core.Domain;
+
+public class BaseCRUDVM : IBaseCRUDVM where TModel : class
{
- public class BaseCRUDVM : IBaseCRUDVM where TModel : class
+ private readonly DataContext _context;
+ internal DbSet dbSet;
+
+ public BaseCRUDVM(DataContext context)
+ {
+ _context = context;
+ this.dbSet = _context.Set();
+ }
+
+ IEnumerable IBaseCRUDVM.Get()
{
- private readonly DataContext _context;
- internal DbSet dbSet;
-
- public BaseCRUDVM(DataContext context)
- {
- _context = context;
- this.dbSet = _context.Set();
- }
-
- IEnumerable IBaseCRUDVM.Get()
- {
- return dbSet.ToList();
- }
-
- TModel IBaseCRUDVM.Get(Expression> express)
- {
- return dbSet.Where(express).FirstOrDefault();
- }
-
- async Task IBaseCRUDVM.GetAsync(Expression> express)
- {
- return await dbSet.Where(express).FirstOrDefaultAsync();
- }
-
- public TModel GetById(object id)
- {
- return dbSet.Find(id);
- }
-
- public async Task GetByIdAsync(object id)
- {
- return await dbSet.FindAsync(id);
- }
-
- public void DoAdd(TModel model)
- {
- _context.Entry(model).CurrentValues["IsDeleted"] = false;
- _context.Entry(model).CurrentValues["AuditStatus"] = "Add";
- _context.Add(model);
- _context.SaveChanges();
- }
-
- public async Task DoAddAsync(TModel model)
- {
- _context.Entry(model).CurrentValues["IsDeleted"] = false;
- _context.Entry(model).CurrentValues["AuditStatus"] = "Add";
- await _context.AddAsync(model);
- await _context.SaveChangesAsync();
- }
-
- public void DoDelete(object id)
- {
- var query = dbSet.Find(id);
- _context.Entry(query).CurrentValues["IsDeleted"] = true;
- _context.Update(query);
- _context.SaveChanges();
- }
-
- public async Task DoDeleteAsync(Guid id, Guid? updateById = null)
- {
- var query = await dbSet.FindAsync(id);
- _context.Entry(query).CurrentValues["IsDeleted"] = true;
- _context.Entry(query).CurrentValues["UpdateBy"] = updateById ?? null;
- _context.Entry(query).CurrentValues["UpdateTime"] = DateTime.Now;
- await _context.SaveChangesAsync();
- }
-
- public void DoRealDelete(object id)
- {
- var query = dbSet.Find(id);
- _context.Remove(query);
- _context.SaveChanges();
- }
-
- public async Task DoRealDeleteAsync(object id)
- {
- var query = await dbSet.FindAsync(id);
- _context.Remove(query);
- await _context.SaveChangesAsync();
- }
-
- public void DoUpdate(TModel model)
- {
- _context.Update(model);
- _context.SaveChanges();
- }
-
- public async Task DoUpdateAsync(TModel model)
- {
- _context.Update(model);
- await _context.SaveChangesAsync();
- }
+ return dbSet.ToList();
+ }
+ TModel IBaseCRUDVM.Get(Expression> express)
+ {
+ return dbSet.Where(express).FirstOrDefault();
+ }
+
+ async Task IBaseCRUDVM.GetAsync(Expression> express)
+ {
+ return await dbSet.Where(express).FirstOrDefaultAsync();
+ }
+ public TModel GetById(object id)
+ {
+ return dbSet.Find(id);
+ }
+
+ public async Task GetByIdAsync(object id)
+ {
+ return await dbSet.FindAsync(id);
+ }
+
+ public void DoAdd(TModel model)
+ {
+ _context.Entry(model).CurrentValues["IsDeleted"] = false;
+ _context.Entry(model).CurrentValues["AuditStatus"] = "Add";
+ _context.Add(model);
+ _context.SaveChanges();
+ }
+
+ public async Task DoAddAsync(TModel model)
+ {
+ _context.Entry(model).CurrentValues["IsDeleted"] = false;
+ _context.Entry(model).CurrentValues["AuditStatus"] = "Add";
+ await _context.AddAsync(model);
+ await _context.SaveChangesAsync();
}
+
+ public void DoDelete(object id)
+ {
+ var query = dbSet.Find(id);
+ _context.Entry(query).CurrentValues["IsDeleted"] = true;
+ _context.Update(query);
+ _context.SaveChanges();
+ }
+
+ public async Task DoDeleteAsync(Guid id, Guid? updateById = null)
+ {
+ var query = await dbSet.FindAsync(id);
+ _context.Entry(query).CurrentValues["IsDeleted"] = true;
+ _context.Entry(query).CurrentValues["UpdateBy"] = updateById ?? null;
+ _context.Entry(query).CurrentValues["UpdateTime"] = DateTime.Now;
+ await _context.SaveChangesAsync();
+ }
+
+ public void DoRealDelete(object id)
+ {
+ var query = dbSet.Find(id);
+ _context.Remove(query);
+ _context.SaveChanges();
+ }
+
+ public async Task DoRealDeleteAsync(object id)
+ {
+ var query = await dbSet.FindAsync(id);
+ _context.Remove(query);
+ await _context.SaveChangesAsync();
+ }
+
+ public void DoUpdate(TModel model)
+ {
+ _context.Update(model);
+ _context.SaveChanges();
+ }
+
+ public async Task DoUpdateAsync(TModel model)
+ {
+ _context.Update(model);
+ await _context.SaveChangesAsync();
+ }
+
+
}
diff --git a/Tiobon.Core.Extensions/AOP/BlogCacheAOP.cs b/Tiobon.Core.Extensions/AOP/BlogCacheAOP.cs
index 4d1e72fe..72f7c3df 100644
--- a/Tiobon.Core.Extensions/AOP/BlogCacheAOP.cs
+++ b/Tiobon.Core.Extensions/AOP/BlogCacheAOP.cs
@@ -1,83 +1,79 @@
-using System;
+using Castle.DynamicProxy;
using Tiobon.Core.Common;
-using Castle.DynamicProxy;
-using System.Linq;
-using System.Threading.Tasks;
using Tiobon.Core.Common.Caches;
-namespace Tiobon.Core.AOP
+namespace Tiobon.Core.AOP;
+
+///
+/// 面向切面的缓存使用
+///
+public class TiobonCacheAOP : CacheAOPbase
{
- ///
- /// 面向切面的缓存使用
- ///
- public class TiobonCacheAOP : CacheAOPbase
- {
- //通过注入的方式,把缓存操作接口通过构造函数注入
- private readonly ICaching _cache;
+ //通过注入的方式,把缓存操作接口通过构造函数注入
+ private readonly ICaching _cache;
- public TiobonCacheAOP(ICaching cache)
- {
- _cache = cache;
- }
+ public TiobonCacheAOP(ICaching cache)
+ {
+ _cache = cache;
+ }
- //Intercept方法是拦截的关键所在,也是IInterceptor接口中的唯一定义
- public override void Intercept(IInvocation invocation)
+ //Intercept方法是拦截的关键所在,也是IInterceptor接口中的唯一定义
+ public override void Intercept(IInvocation invocation)
+ {
+ var method = invocation.MethodInvocationTarget ?? invocation.Method;
+ //对当前方法的特性验证
+ //如果需要验证
+ var CachingAttribute = method.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(CachingAttribute));
+ if (CachingAttribute is CachingAttribute qCachingAttribute)
{
- var method = invocation.MethodInvocationTarget ?? invocation.Method;
- //对当前方法的特性验证
- //如果需要验证
- var CachingAttribute = method.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(CachingAttribute));
- if (CachingAttribute is CachingAttribute qCachingAttribute)
+ //获取自定义缓存键
+ var cacheKey = CustomCacheKey(invocation);
+ if (_cache.Exists(cacheKey))
{
- //获取自定义缓存键
- var cacheKey = CustomCacheKey(invocation);
- if (_cache.Exists(cacheKey))
+ //将当前获取到的缓存值,赋值给当前执行方法
+ Type returnType;
+ if (typeof(Task).IsAssignableFrom(method.ReturnType))
{
- //将当前获取到的缓存值,赋值给当前执行方法
- Type returnType;
- if (typeof(Task).IsAssignableFrom(method.ReturnType))
- {
- returnType = method.ReturnType.GenericTypeArguments.FirstOrDefault();
- }
- else
- {
- returnType = method.ReturnType;
- }
-
- //根据key获取相应的缓存值
- dynamic cacheValue = _cache.Get(returnType, cacheKey);
- invocation.ReturnValue = (typeof(Task).IsAssignableFrom(method.ReturnType)) ? Task.FromResult(cacheValue) : cacheValue;
- return;
+ returnType = method.ReturnType.GenericTypeArguments.FirstOrDefault();
}
-
- //去执行当前的方法
- invocation.Proceed();
- //存入缓存
- if (!string.IsNullOrWhiteSpace(cacheKey))
+ else
{
- object response;
+ returnType = method.ReturnType;
+ }
- //Type type = invocation.ReturnValue?.GetType();
- var type = invocation.Method.ReturnType;
- if (typeof(Task).IsAssignableFrom(type))
- {
- dynamic result = invocation.ReturnValue;
- response = result.Result;
- }
- else
- {
- response = invocation.ReturnValue;
- }
+ //根据key获取相应的缓存值
+ dynamic cacheValue = _cache.Get(returnType, cacheKey);
+ invocation.ReturnValue = (typeof(Task).IsAssignableFrom(method.ReturnType)) ? Task.FromResult(cacheValue) : cacheValue;
+ return;
+ }
- if (response == null) response = string.Empty;
+ //去执行当前的方法
+ invocation.Proceed();
+ //存入缓存
+ if (!string.IsNullOrWhiteSpace(cacheKey))
+ {
+ object response;
- _cache.Set(cacheKey, response, TimeSpan.FromMinutes(qCachingAttribute.AbsoluteExpiration));
+ //Type type = invocation.ReturnValue?.GetType();
+ var type = invocation.Method.ReturnType;
+ if (typeof(Task).IsAssignableFrom(type))
+ {
+ dynamic result = invocation.ReturnValue;
+ response = result.Result;
}
+ else
+ {
+ response = invocation.ReturnValue;
+ }
+
+ if (response == null) response = string.Empty;
+
+ _cache.Set(cacheKey, response, TimeSpan.FromMinutes(qCachingAttribute.AbsoluteExpiration));
}
- else
- {
- invocation.Proceed(); //直接执行被拦截方法
- }
+ }
+ else
+ {
+ invocation.Proceed(); //直接执行被拦截方法
}
}
}
\ No newline at end of file
diff --git a/Tiobon.Core.Extensions/AOP/BlogLogAOP.cs b/Tiobon.Core.Extensions/AOP/BlogLogAOP.cs
index 617e3ef0..14d01424 100644
--- a/Tiobon.Core.Extensions/AOP/BlogLogAOP.cs
+++ b/Tiobon.Core.Extensions/AOP/BlogLogAOP.cs
@@ -1,291 +1,287 @@
-using Tiobon.Core.Common;
-using Tiobon.Core.Common.LogHelper;
-using Tiobon.Core.Hubs;
-using Castle.DynamicProxy;
+using Castle.DynamicProxy;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.SignalR;
using Newtonsoft.Json;
using StackExchange.Profiling;
-using System;
-using System.Linq;
using System.Reflection;
-using System.Threading.Tasks;
+using Tiobon.Core.Common;
+using Tiobon.Core.Common.LogHelper;
+using Tiobon.Core.Hubs;
+
+namespace Tiobon.Core.AOP;
-namespace Tiobon.Core.AOP
+///
+/// 拦截器TiobonLogAOP 继承IInterceptor接口
+///
+public class TiobonLogAOP : IInterceptor
{
+ private readonly IHubContext _hubContext;
+ private readonly IHttpContextAccessor _accessor;
+
+ public TiobonLogAOP(IHubContext hubContext, IHttpContextAccessor accessor)
+ {
+ _hubContext = hubContext;
+ _accessor = accessor;
+ }
+
+
///
- /// 拦截器TiobonLogAOP 继承IInterceptor接口
+ /// 实例化IInterceptor唯一方法
///
- public class TiobonLogAOP : IInterceptor
+ /// 包含被拦截方法的信息
+ public void Intercept(IInvocation invocation)
{
- private readonly IHubContext _hubContext;
- private readonly IHttpContextAccessor _accessor;
-
- public TiobonLogAOP(IHubContext hubContext, IHttpContextAccessor accessor)
+ string UserName = _accessor.HttpContext?.User?.Identity?.Name;
+ string json;
+ try
{
- _hubContext = hubContext;
- _accessor = accessor;
+ json = JsonConvert.SerializeObject(invocation.Arguments);
+ }
+ catch (Exception ex)
+ {
+ json = "无法序列化,可能是兰姆达表达式等原因造成,按照框架优化代码" + ex.ToString();
}
-
- ///
- /// 实例化IInterceptor唯一方法
- ///
- /// 包含被拦截方法的信息
- public void Intercept(IInvocation invocation)
+ DateTime startTime = DateTime.Now;
+ AOPLogInfo apiLogAopInfo = new AOPLogInfo
{
- string UserName = _accessor.HttpContext?.User?.Identity?.Name;
- string json;
- try
- {
- json = JsonConvert.SerializeObject(invocation.Arguments);
- }
- catch (Exception ex)
- {
- json = "无法序列化,可能是兰姆达表达式等原因造成,按照框架优化代码" + ex.ToString();
- }
+ RequestTime = startTime.ToString("yyyy-MM-dd hh:mm:ss fff"),
+ OpUserName = UserName,
+ RequestMethodName = invocation.Method.Name,
+ RequestParamsName = string.Join(", ", invocation.Arguments.Select(a => (a ?? "").ToString()).ToArray()),
+ ResponseJsonData = json
+ };
- DateTime startTime = DateTime.Now;
- AOPLogInfo apiLogAopInfo = new AOPLogInfo
- {
- RequestTime = startTime.ToString("yyyy-MM-dd hh:mm:ss fff"),
- OpUserName = UserName,
- RequestMethodName = invocation.Method.Name,
- RequestParamsName = string.Join(", ", invocation.Arguments.Select(a => (a ?? "").ToString()).ToArray()),
- ResponseJsonData = json
- };
+ //测试异常记录
+ //Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss fff"));
+
+ //记录被拦截方法信息的日志信息
+ //var dataIntercept = "" +
+ // $"【当前操作用户】:{ UserName} \r\n" +
+ // $"【当前执行方法】:{ invocation.Method.Name} \r\n" +
+ // $"【携带的参数有】: {string.Join(", ", invocation.Arguments.Select(a => (a ?? "").ToString()).ToArray())} \r\n";
- //测试异常记录
- //Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss fff"));
+ try
+ {
+ MiniProfiler.Current.Step($"执行Service方法:{invocation.Method.Name}() -> ");
+ //在被拦截的方法执行完毕后 继续执行当前方法,注意是被拦截的是异步的
+ invocation.Proceed();
- //记录被拦截方法信息的日志信息
- //var dataIntercept = "" +
- // $"【当前操作用户】:{ UserName} \r\n" +
- // $"【当前执行方法】:{ invocation.Method.Name} \r\n" +
- // $"【携带的参数有】: {string.Join(", ", invocation.Arguments.Select(a => (a ?? "").ToString()).ToArray())} \r\n";
- try
+ // 异步获取异常,先执行
+ if (IsAsyncMethod(invocation.Method))
{
- MiniProfiler.Current.Step($"执行Service方法:{invocation.Method.Name}() -> ");
- //在被拦截的方法执行完毕后 继续执行当前方法,注意是被拦截的是异步的
- invocation.Proceed();
-
+ #region 方案一
- // 异步获取异常,先执行
- if (IsAsyncMethod(invocation.Method))
+ //Wait task execution and modify return value
+ if (invocation.Method.ReturnType == typeof(Task))
{
- #region 方案一
-
- //Wait task execution and modify return value
- if (invocation.Method.ReturnType == typeof(Task))
- {
- invocation.ReturnValue = InternalAsyncHelper.AwaitTaskWithPostActionAndFinally(
- (Task) invocation.ReturnValue,
- async () => await SuccessAction(invocation, apiLogAopInfo, startTime), /*成功时执行*/
- ex =>
- {
- LogEx(ex, apiLogAopInfo);
- });
- }
- //Task
- else
- {
- invocation.ReturnValue = InternalAsyncHelper.CallAwaitTaskWithPostActionAndFinallyAndGetResult(
- invocation.Method.ReturnType.GenericTypeArguments[0],
- invocation.ReturnValue,
- //async () => await SuccessAction(invocation, dataIntercept),/*成功时执行*/
- async (o) => await SuccessAction(invocation, apiLogAopInfo, startTime, o), /*成功时执行*/
- ex =>
- {
- LogEx(ex, apiLogAopInfo);
- });
- }
-
- #endregion
-
-
- // 如果方案一不行,试试这个方案
- //#region 方案二
-
- //var type = invocation.Method.ReturnType;
- //var resultProperty = type.GetProperty("Result");
- //DateTime endTime = DateTime.Now;
- //string ResponseTime = (endTime - startTime).Milliseconds.ToString();
- //apiLogAopInfo.ResponseTime = endTime.ToString("yyyy-MM-dd hh:mm:ss fff");
- //apiLogAopInfo.ResponseIntervalTime = ResponseTime + "ms";
- //apiLogAopInfo.ResponseJsonData = JsonConvert.SerializeObject(resultProperty.GetValue(invocation.ReturnValue));
-
- ////dataIntercept += ($"【响应时间】:{ResponseTime}ms\r\n");
- ////dataIntercept += ($"【执行完成时间】:{endTime.ToString("yyyy-MM-dd hh:mm:ss fff")}\r\n");
- ////dataIntercept += ($"【执行完成结果】:{JsonConvert.SerializeObject(resultProperty.GetValue(invocation.ReturnValue))}\r\n");
-
- //Parallel.For(0, 1, e =>
- //{
- // //LogLock.OutLogAOP("AOPLog", new string[] { dataIntercept });
- // LogLock.OutLogAOP("AOPLog", new string[] { apiLogAopInfo.GetType().ToString() + " - ResponseJsonDataType:" + type, JsonConvert.SerializeObject(apiLogAopInfo) });
- //});
-
- //#endregion
+ invocation.ReturnValue = InternalAsyncHelper.AwaitTaskWithPostActionAndFinally(
+ (Task) invocation.ReturnValue,
+ async () => await SuccessAction(invocation, apiLogAopInfo, startTime), /*成功时执行*/
+ ex =>
+ {
+ LogEx(ex, apiLogAopInfo);
+ });
}
+ //Task
else
{
- // 同步1
- string jsonResult;
- try
- {
- jsonResult = JsonConvert.SerializeObject(invocation.ReturnValue);
- }
- catch (Exception ex)
- {
- jsonResult = "无法序列化,可能是兰姆达表达式等原因造成,按照框架优化代码" + ex.ToString();
- }
-
- var type = invocation.Method.ReturnType;
- var resultProperty = type.GetProperty("Result");
- DateTime endTime = DateTime.Now;
- string ResponseTime = (endTime - startTime).Milliseconds.ToString();
- apiLogAopInfo.ResponseTime = endTime.ToString("yyyy-MM-dd hh:mm:ss fff");
- apiLogAopInfo.ResponseIntervalTime = ResponseTime + "ms";
- //apiLogAopInfo.ResponseJsonData = JsonConvert.SerializeObject(resultProperty.GetValue(invocation.ReturnValue));
- apiLogAopInfo.ResponseJsonData = jsonResult;
- //dataIntercept += ($"【执行完成结果】:{jsonResult}");
- Parallel.For(0, 1, e =>
- {
- //LogLock.OutLogAOP("AOPLog", new string[] { dataIntercept });
- LogLock.OutLogAOP("AOPLog", _accessor.HttpContext?.TraceIdentifier,
- new string[] {apiLogAopInfo.GetType().ToString(), JsonConvert.SerializeObject(apiLogAopInfo)});
- });
+ invocation.ReturnValue = InternalAsyncHelper.CallAwaitTaskWithPostActionAndFinallyAndGetResult(
+ invocation.Method.ReturnType.GenericTypeArguments[0],
+ invocation.ReturnValue,
+ //async () => await SuccessAction(invocation, dataIntercept),/*成功时执行*/
+ async (o) => await SuccessAction(invocation, apiLogAopInfo, startTime, o), /*成功时执行*/
+ ex =>
+ {
+ LogEx(ex, apiLogAopInfo);
+ });
}
- }
- catch (Exception ex) // 同步2
- {
- LogEx(ex, apiLogAopInfo);
- throw;
- }
- if (AppSettings.app(new string[] {"Middleware", "SignalRSendLog", "Enabled"}).ObjToBool())
- {
- _hubContext.Clients.All.SendAsync("ReceiveUpdate", LogLock.GetLogData()).Wait();
- }
- }
+ #endregion
- private async Task SuccessAction(IInvocation invocation, AOPLogInfo apiLogAopInfo, DateTime startTime, object o = null)
- {
- //invocation.ReturnValue = o;
- //var type = invocation.Method.ReturnType;
- //if (typeof(Task).IsAssignableFrom(type))
- //{
- // //var resultProperty = type.GetProperty("Result");
- // //类型错误 都可以不要invocation参数,直接将o系列化保存到日记中
- // dataIntercept += ($"【执行完成结果】:{JsonConvert.SerializeObject(invocation.ReturnValue)}");
- //}
- //else
- //{
- // dataIntercept += ($"【执行完成结果】:{invocation.ReturnValue}");
- //}
- DateTime endTime = DateTime.Now;
- string ResponseTime = (endTime - startTime).Milliseconds.ToString();
- apiLogAopInfo.ResponseTime = endTime.ToString("yyyy-MM-dd hh:mm:ss fff");
- apiLogAopInfo.ResponseIntervalTime = ResponseTime + "ms";
- apiLogAopInfo.ResponseJsonData = JsonConvert.SerializeObject(o);
-
-
- await Task.Run(() =>
+
+ // 如果方案一不行,试试这个方案
+ //#region 方案二
+
+ //var type = invocation.Method.ReturnType;
+ //var resultProperty = type.GetProperty("Result");
+ //DateTime endTime = DateTime.Now;
+ //string ResponseTime = (endTime - startTime).Milliseconds.ToString();
+ //apiLogAopInfo.ResponseTime = endTime.ToString("yyyy-MM-dd hh:mm:ss fff");
+ //apiLogAopInfo.ResponseIntervalTime = ResponseTime + "ms";
+ //apiLogAopInfo.ResponseJsonData = JsonConvert.SerializeObject(resultProperty.GetValue(invocation.ReturnValue));
+
+ ////dataIntercept += ($"【响应时间】:{ResponseTime}ms\r\n");
+ ////dataIntercept += ($"【执行完成时间】:{endTime.ToString("yyyy-MM-dd hh:mm:ss fff")}\r\n");
+ ////dataIntercept += ($"【执行完成结果】:{JsonConvert.SerializeObject(resultProperty.GetValue(invocation.ReturnValue))}\r\n");
+
+ //Parallel.For(0, 1, e =>
+ //{
+ // //LogLock.OutLogAOP("AOPLog", new string[] { dataIntercept });
+ // LogLock.OutLogAOP("AOPLog", new string[] { apiLogAopInfo.GetType().ToString() + " - ResponseJsonDataType:" + type, JsonConvert.SerializeObject(apiLogAopInfo) });
+ //});
+
+ //#endregion
+ }
+ else
{
+ // 同步1
+ string jsonResult;
+ try
+ {
+ jsonResult = JsonConvert.SerializeObject(invocation.ReturnValue);
+ }
+ catch (Exception ex)
+ {
+ jsonResult = "无法序列化,可能是兰姆达表达式等原因造成,按照框架优化代码" + ex.ToString();
+ }
+
+ var type = invocation.Method.ReturnType;
+ var resultProperty = type.GetProperty("Result");
+ DateTime endTime = DateTime.Now;
+ string ResponseTime = (endTime - startTime).Milliseconds.ToString();
+ apiLogAopInfo.ResponseTime = endTime.ToString("yyyy-MM-dd hh:mm:ss fff");
+ apiLogAopInfo.ResponseIntervalTime = ResponseTime + "ms";
+ //apiLogAopInfo.ResponseJsonData = JsonConvert.SerializeObject(resultProperty.GetValue(invocation.ReturnValue));
+ apiLogAopInfo.ResponseJsonData = jsonResult;
+ //dataIntercept += ($"【执行完成结果】:{jsonResult}");
Parallel.For(0, 1, e =>
{
- //LogLock.OutSql2Log("AOPLog", new string[] { JsonConvert.SerializeObject(apiLogAopInfo) });
+ //LogLock.OutLogAOP("AOPLog", new string[] { dataIntercept });
LogLock.OutLogAOP("AOPLog", _accessor.HttpContext?.TraceIdentifier,
new string[] {apiLogAopInfo.GetType().ToString(), JsonConvert.SerializeObject(apiLogAopInfo)});
});
- });
+ }
}
-
- private void LogEx(Exception ex, AOPLogInfo dataIntercept)
+ catch (Exception ex) // 同步2
{
- if (ex != null)
- {
- //执行的 service 中,收录异常
- MiniProfiler.Current.CustomTiming("Errors:", ex.Message);
- //执行的 service 中,捕获异常
- //dataIntercept += ($"【执行完成结果】:方法中出现异常:{ex.Message + ex.InnerException}\r\n");
- AOPLogExInfo apiLogAopExInfo = new AOPLogExInfo
- {
- ExMessage = ex.Message,
- InnerException = "InnerException-内部异常:\r\n" + (ex.InnerException == null ? "" : ex.InnerException.InnerException.ToString()) +
- ("\r\nStackTrace-堆栈跟踪:\r\n") + (ex.StackTrace == null ? "" : ex.StackTrace.ToString()),
- ApiLogAopInfo = dataIntercept
- };
- // 异常日志里有详细的堆栈信息
- Parallel.For(0, 1, e =>
- {
- //LogLock.OutLogAOP("AOPLogEx", new string[] { dataIntercept });
- LogLock.OutLogAOP("AOPLogEx", _accessor.HttpContext?.TraceIdentifier,
- new string[] {apiLogAopExInfo.GetType().ToString(), JsonConvert.SerializeObject(apiLogAopExInfo)});
- });
- }
+ LogEx(ex, apiLogAopInfo);
+ throw;
}
-
- public static bool IsAsyncMethod(MethodInfo method)
+ if (AppSettings.app(new string[] {"Middleware", "SignalRSendLog", "Enabled"}).ObjToBool())
{
- return (
- method.ReturnType == typeof(Task) ||
- (method.ReturnType.IsGenericType && method.ReturnType.GetGenericTypeDefinition() == typeof(Task<>))
- );
+ _hubContext.Clients.All.SendAsync("ReceiveUpdate", LogLock.GetLogData()).Wait();
}
}
-
- internal static class InternalAsyncHelper
+ private async Task SuccessAction(IInvocation invocation, AOPLogInfo apiLogAopInfo, DateTime startTime, object o = null)
{
- public static async Task AwaitTaskWithPostActionAndFinally(Task actualReturnValue, Func postAction, Action finalAction)
- {
- Exception exception = null;
+ //invocation.ReturnValue = o;
+ //var type = invocation.Method.ReturnType;
+ //if (typeof(Task).IsAssignableFrom(type))
+ //{
+ // //var resultProperty = type.GetProperty("Result");
+ // //类型错误 都可以不要invocation参数,直接将o系列化保存到日记中
+ // dataIntercept += ($"【执行完成结果】:{JsonConvert.SerializeObject(invocation.ReturnValue)}");
+ //}
+ //else
+ //{
+ // dataIntercept += ($"【执行完成结果】:{invocation.ReturnValue}");
+ //}
+ DateTime endTime = DateTime.Now;
+ string ResponseTime = (endTime - startTime).Milliseconds.ToString();
+ apiLogAopInfo.ResponseTime = endTime.ToString("yyyy-MM-dd hh:mm:ss fff");
+ apiLogAopInfo.ResponseIntervalTime = ResponseTime + "ms";
+ apiLogAopInfo.ResponseJsonData = JsonConvert.SerializeObject(o);
- try
+
+ await Task.Run(() =>
+ {
+ Parallel.For(0, 1, e =>
{
- await actualReturnValue;
- await postAction();
- }
- catch (Exception ex)
+ //LogLock.OutSql2Log("AOPLog", new string[] { JsonConvert.SerializeObject(apiLogAopInfo) });
+ LogLock.OutLogAOP("AOPLog", _accessor.HttpContext?.TraceIdentifier,
+ new string[] {apiLogAopInfo.GetType().ToString(), JsonConvert.SerializeObject(apiLogAopInfo)});
+ });
+ });
+ }
+
+ private void LogEx(Exception ex, AOPLogInfo dataIntercept)
+ {
+ if (ex != null)
+ {
+ //执行的 service 中,收录异常
+ MiniProfiler.Current.CustomTiming("Errors:", ex.Message);
+ //执行的 service 中,捕获异常
+ //dataIntercept += ($"【执行完成结果】:方法中出现异常:{ex.Message + ex.InnerException}\r\n");
+ AOPLogExInfo apiLogAopExInfo = new AOPLogExInfo
{
- exception = ex;
- }
- finally
+ ExMessage = ex.Message,
+ InnerException = "InnerException-内部异常:\r\n" + (ex.InnerException == null ? "" : ex.InnerException.InnerException.ToString()) +
+ ("\r\nStackTrace-堆栈跟踪:\r\n") + (ex.StackTrace == null ? "" : ex.StackTrace.ToString()),
+ ApiLogAopInfo = dataIntercept
+ };
+ // 异常日志里有详细的堆栈信息
+ Parallel.For(0, 1, e =>
{
- finalAction(exception);
- }
+ //LogLock.OutLogAOP("AOPLogEx", new string[] { dataIntercept });
+ LogLock.OutLogAOP("AOPLogEx", _accessor.HttpContext?.TraceIdentifier,
+ new string[] {apiLogAopExInfo.GetType().ToString(), JsonConvert.SerializeObject(apiLogAopExInfo)});
+ });
}
+ }
+
+
+ public static bool IsAsyncMethod(MethodInfo method)
+ {
+ return (
+ method.ReturnType == typeof(Task) ||
+ (method.ReturnType.IsGenericType && method.ReturnType.GetGenericTypeDefinition() == typeof(Task<>))
+ );
+ }
+}
- public static async Task AwaitTaskWithPostActionAndFinallyAndGetResult(Task actualReturnValue, Func