/// <summary> /// 实例化IInterceptor唯一方法 /// </summary> /// <param name="invocation">包含被拦截方法的信息</param> public void Intercept(IInvocation invocation) { var method = invocation.MethodInvocationTarget ?? invocation.Method; //对当前方法的特性验证 //如果需要验证 if (method.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(UseTranAttribute)) is UseTranAttribute) { try { Console.WriteLine($"Begin Transaction"); _unitOfWork.BeginTran(); invocation.Proceed(); // 异步获取异常,先执行 if (IsAsyncMethod(invocation.Method)) { if (invocation.Method.ReturnType == typeof(Task)) { invocation.ReturnValue = InternalAsyncHelper.AwaitTaskWithPostActionAndFinally( (Task)invocation.ReturnValue, async() => await SuccessAction(invocation),/*成功时执行*/ ex => { _unitOfWork.RollbackTran(); }); } else //Task<TResult> { invocation.ReturnValue = InternalAsyncHelper.CallAwaitTaskWithPostActionAndFinallyAndGetResult( invocation.Method.ReturnType.GenericTypeArguments[0], invocation.ReturnValue, async() => await SuccessAction(invocation),/*成功时执行*/ ex => { _unitOfWork.RollbackTran(); }); } } _unitOfWork.CommitTran(); } catch (Exception) { Console.WriteLine($"Rollback Transaction"); _unitOfWork.RollbackTran(); } } else { invocation.Proceed();//直接执行被拦截方法 } }
/// <summary> /// 实例化IInterceptor唯一方法 /// </summary> /// <param name="invocation">包含被拦截方法的信息</param> public void Intercept(IInvocation invocation) { string UserName = _accessor.HttpContext?.User?.Identity?.Name; //记录被拦截方法信息的日志信息 var dataIntercept = "" + $"【当前操作用户】:{ UserName} \r\n" + $"【当前执行方法】:{ invocation.Method.Name} \r\n" + $"【携带的参数有】: {string.Join(", ", invocation.Arguments.Select(a => (a ?? "").ToString()).ToArray())} \r\n"; try { MiniProfiler.Current.Step($"执行Service方法:{invocation.Method.Name}() -> "); //在被拦截的方法执行完毕后 继续执行当前方法,注意是被拦截的是异步的 invocation.Proceed(); // 异步获取异常,先执行 if (IsAsyncMethod(invocation.Method)) { //Wait task execution and modify return value if (invocation.Method.ReturnType == typeof(Task)) { invocation.ReturnValue = InternalAsyncHelper.AwaitTaskWithPostActionAndFinally( (Task)invocation.ReturnValue, async() => await SuccessAction(invocation, dataIntercept), /*成功时执行*/ ex => { LogEx(ex, dataIntercept); }); } else //Task<TResult> { invocation.ReturnValue = InternalAsyncHelper.CallAwaitTaskWithPostActionAndFinallyAndGetResult( invocation.Method.ReturnType.GenericTypeArguments[0], invocation.ReturnValue, async() => await SuccessAction(invocation, dataIntercept),/*成功时执行*/ ex => { LogEx(ex, dataIntercept); }); } } else {// 同步1 } } catch (Exception ex)// 同步2 { LogEx(ex, dataIntercept); } _hubContext.Clients.All.SendAsync("ReceiveUpdate", LogLock.GetLogData()).Wait(); }
/// <summary> /// 实例化IInterceptor唯一方法 /// </summary> /// <param name="invocation">包含被拦截方法的信息</param> public void Intercept(IInvocation invocation) { //记录被拦截方法信息的日志信息 var dataIntercept = "" + $"【当前执行方法】:{ invocation.Method.Name} \r\n" + $"【携带的参数有】: {string.Join(", ", invocation.Arguments.Select(a => (a ?? "").ToString()).ToArray())} \r\n"; try { MiniProfiler.Current.Step($"执行Service方法:{invocation.Method.Name}() -> "); //在被拦截的方法执行完毕后 继续执行当前方法,注意是被拦截的是异步的 invocation.Proceed(); // 异步获取异常,先执行 if (IsAsyncMethod(invocation.Method)) { //Wait task execution and modify return value if (invocation.Method.ReturnType == typeof(Task)) { invocation.ReturnValue = InternalAsyncHelper.AwaitTaskWithPostActionAndFinally( (Task)invocation.ReturnValue, async() => await TestActionAsync(invocation), ex => { LogEx(ex, ref dataIntercept); }); } else //Task<TResult> { invocation.ReturnValue = InternalAsyncHelper.CallAwaitTaskWithPostActionAndFinallyAndGetResult( invocation.Method.ReturnType.GenericTypeArguments[0], invocation.ReturnValue, async() => await TestActionAsync(invocation), ex => { LogEx(ex, ref dataIntercept); }); } } else {// 同步1 } } catch (Exception ex)// 同步2 { LogEx(ex, ref dataIntercept); } var type = invocation.Method.ReturnType; if (typeof(Task).IsAssignableFrom(type)) { var resultProperty = type.GetProperty("Result"); dataIntercept += ($"【执行完成结果】:{JsonConvert.SerializeObject(resultProperty.GetValue(invocation.ReturnValue))}"); } else { dataIntercept += ($"【执行完成结果】:{invocation.ReturnValue}"); } Parallel.For(0, 1, e => { LogLock.OutSql2Log("AOPLog", new string[] { dataIntercept }); }); _hubContext.Clients.All.SendAsync("ReceiveUpdate", LogLock.GetLogData()).Wait(); }
/// <summary> /// 实例化IInterceptor唯一方法 /// </summary> /// <param name="invocation">包含被拦截方法的信息</param> public void Intercept(IInvocation invocation) { string UserName = _accessor.HttpContext?.User?.Identity?.Name; string json; try { json = JsonConvert.SerializeObject(invocation.Arguments); } catch (Exception ex) { json = "无法序列化,可能是兰姆达表达式等原因造成,按照框架优化代码" + ex.ToString(); } DateTime startTime = DateTime.Now; ApiLogAopInfo apiLogAopInfo = new ApiLogAopInfo { 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"; try { MiniProfiler.Current.Step($"执行Service方法:{invocation.Method.Name}() -> "); //在被拦截的方法执行完毕后 继续执行当前方法,注意是被拦截的是异步的 invocation.Proceed(); // 异步获取异常,先执行 if (IsAsyncMethod(invocation.Method)) { #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<TResult> 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.OutSql2Log("AOPLog", new string[] { JsonConvert.SerializeObject(apiLogAopInfo) }); //}); #endregion } else { // 同步1 string jsonResult; try { jsonResult = JsonConvert.SerializeObject(invocation.ReturnValue); } catch (Exception ex) { jsonResult = "无法序列化,可能是兰姆达表达式等原因造成,按照框架优化代码" + ex.ToString(); } apiLogAopInfo.ResponseJsonData = jsonResult; Parallel.For(0, 1, e => { LogLock.OutSql2Log("AOPLog", new string[] { JsonConvert.SerializeObject(apiLogAopInfo) }); }); } } catch (Exception ex)// 同步2 { LogEx(ex, apiLogAopInfo); } if (Appsettings.app(new string[] { "Middleware", "SignalRSendLog", "Enabled" }).ObjToBool()) { _hubContext.Clients.All.SendAsync("ReceiveUpdate", LogLock.GetLogData()).Wait(); } }
/// <summary> /// 实例化IInterceptor唯一方法 /// </summary> /// <param name="invocation">包含被拦截方法的信息</param> public void Intercept(IInvocation invocation) { string UserName = _accessor.HttpContext?.User?.Identity?.Name; //记录被拦截方法信息的日志信息 var dataIntercept = "" + $"【当前操作用户】:{ UserName} \r\n" + $"【当前执行方法】:{ invocation.Method.Name} \r\n" + $"【携带的参数有】: {string.Join(", ", invocation.Arguments.Select(a => (a ?? "").ToString()).ToArray())} \r\n"; try { MiniProfiler.Current.Step($"执行Service方法:{invocation.Method.Name}() -> "); //在被拦截的方法执行完毕后 继续执行当前方法,注意是被拦截的是异步的 invocation.Proceed(); // 异步获取异常,先执行 if (IsAsyncMethod(invocation.Method)) { #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, dataIntercept), /*成功时执行*/ ex => { LogEx(ex, dataIntercept); }); } //Task<TResult> else { invocation.ReturnValue = InternalAsyncHelper.CallAwaitTaskWithPostActionAndFinallyAndGetResult( invocation.Method.ReturnType.GenericTypeArguments[0], invocation.ReturnValue, //async () => await SuccessAction(invocation, dataIntercept),/*成功时执行*/ async(o) => await SuccessAction(invocation, dataIntercept, o),/*成功时执行*/ ex => { LogEx(ex, dataIntercept); }); } #endregion // 如果方案一不行,试试这个方案 #region 方案二 //var type = invocation.Method.ReturnType; //var resultProperty = type.GetProperty("Result"); //dataIntercept += ($"【执行完成结果】:{JsonConvert.SerializeObject(resultProperty.GetValue(invocation.ReturnValue))}"); //Parallel.For(0, 1, e => //{ // LogLock.OutSql2Log("AOPLog", new string[] { dataIntercept }); //}); #endregion } else {// 同步1 dataIntercept += ($"【执行完成结果】:{invocation.ReturnValue}"); Parallel.For(0, 1, e => { LogLock.OutSql2Log("AOPLog", new string[] { dataIntercept }); }); } } catch (Exception ex)// 同步2 { LogEx(ex, dataIntercept); } _hubContext.Clients.All.SendAsync("ReceiveUpdate", LogLock.GetLogData()).Wait(); }
/// <summary> /// 实例化IInterceptor唯一方法 /// </summary> /// <param name="invocation">包含被拦截方法的信息</param> public void Intercept(IInvocation invocation) { //记录被拦截方法信息的日志信息 var dataIntercept = "" + $"【当前执行方法】:{ invocation.Method.Name} \r\n" + $"【携带的参数有】: {string.Join(", ", invocation.Arguments.Select(a => (a ?? "").ToString()).ToArray())} \r\n"; try { MiniProfiler.Current.Step($"执行Service方法:{invocation.Method.Name}() -> "); //在被拦截的方法执行完毕后 继续执行当前方法,注意是被拦截的是异步的 invocation.Proceed(); // 异步获取异常,先执行 if (IsAsyncMethod(invocation.Method)) { //Wait task execution and modify return value if (invocation.Method.ReturnType == typeof(Task)) { invocation.ReturnValue = InternalAsyncHelper.AwaitTaskWithPostActionAndFinally( (Task)invocation.ReturnValue, async() => await TestActionAsync(invocation), ex => { LogEx(ex, ref dataIntercept); }); } else //Task<TResult> { invocation.ReturnValue = InternalAsyncHelper.CallAwaitTaskWithPostActionAndFinallyAndGetResult( invocation.Method.ReturnType.GenericTypeArguments[0], invocation.ReturnValue, async() => await TestActionAsync(invocation), ex => { LogEx(ex, ref dataIntercept); }); } } else // 同步1 { } } catch (Exception ex)// 同步2 { LogEx(ex, ref dataIntercept); } dataIntercept += ($"【执行完成结果】:{invocation.ReturnValue}"); Parallel.For(0, 1, e => { LogLock log = new LogLock(); LogLock.OutSql2Log("AOPLog", new string[] { dataIntercept }); }); _hubContext.Clients.All.SendAsync("ReceiveUpdate", LogLock.GetLogData()).Wait(); #region //输出到当前项目日志,多线程可能会出现争抢资源的问题,舍弃// //var path = Directory.GetCurrentDirectory() + @"\Log"; //if (!Directory.Exists(path)) //{ // Directory.CreateDirectory(path); //} //string fileName = path + $@"\AOPLog.log"; //StreamWriter sw = File.AppendText(fileName); //sw.WriteLine(dataIntercept); //sw.WriteLine(); //sw.Close(); #endregion }
/// <summary> /// 实例化IInterceptor唯一方法 /// </summary> /// <param name="invocation">包含被拦截方法的信息</param> public void Intercept(IInvocation invocation) { //记录被拦截方法信息的日志信息 var dataIntercept = "" + $"【API接口路径】:{ _accessor.HttpContext.Request.Path.Value} \r\n" + $"【当前执行方法】:{ invocation.Method.Name} \r\n" + $"【携带的参数类型】: {string.Join(", ", invocation.Arguments.Select(a => (a ?? "").ToString()).ToArray())} \r\n"; try { MiniProfiler.Current.Step($"执行Service方法:{invocation.Method.Name}() -> "); //获取QueryString值 if (!string.IsNullOrEmpty(_accessor.HttpContext.Request.QueryString.Value)) { Dictionary <string, string> jsonQuery = new Dictionary <string, string>(); for (int i = 0; i < _accessor.HttpContext.Request.Query.Keys.Count; i++) { string[] strqueryjson = new string[_accessor.HttpContext.Request.Query.Keys.Count]; _accessor.HttpContext.Request.Query.Keys.CopyTo(strqueryjson, 0); jsonQuery.Add(strqueryjson[i], _accessor.HttpContext.Request.Query[strqueryjson[i]].FirstOrDefault()); } dataIntercept += $"【当前方法传入的参数Query】:{Newtonsoft.Json.JsonConvert.SerializeObject(jsonQuery)} \r\n"; } //获取Body值 else { _accessor.HttpContext.Request.Body.Position = 0; var requestReader = new StreamReader(_accessor.HttpContext.Request.Body); var requestContent = requestReader.ReadToEnd(); dataIntercept += $"【当前方法传入的参数Body】:{ requestContent} \r\n"; } dataIntercept += $"【当前用户】:{ _user.Name} \r\n"; //在被拦截的方法执行完毕后 继续执行当前方法,注意是被拦截的是异步的 invocation.Proceed(); // 存储响应数据 dataIntercept += $"【返回提示信息】:{ Newtonsoft.Json.JsonConvert.SerializeObject(invocation.ReturnValue)} \r\n"; // 异步获取异常,先执行 if (IsAsyncMethod(invocation.Method)) { //Wait task execution and modify return value if (invocation.Method.ReturnType == typeof(Task)) { invocation.ReturnValue = InternalAsyncHelper.AwaitTaskWithPostActionAndFinally( (Task)invocation.ReturnValue, async() => await TestActionAsync(invocation), ex => { LogEx(ex, ref dataIntercept); }); } else //Task<TResult> { invocation.ReturnValue = InternalAsyncHelper.CallAwaitTaskWithPostActionAndFinallyAndGetResult( invocation.Method.ReturnType.GenericTypeArguments[0], invocation.ReturnValue, async() => await TestActionAsync(invocation), ex => { LogEx(ex, ref dataIntercept); }); } } else {// 同步1 } } catch (Exception ex)// 同步2 { LogEx(ex, ref dataIntercept); } //执行完返回结果数据 dataIntercept += ($"【执行完成结果参数类型】:{invocation.ReturnValue}"); Parallel.For(0, 1, e => { //日志写入 LogLock.OutSql2Log(DateTime.Now.ToString("yyyyMMddHH"), new string[] { dataIntercept }); }); _hubContext.Clients.All.SendAsync("ReceiveUpdate", LogLock.GetLogData()).Wait(); }