コード例 #1
0
        /// <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 += ($"【执行完成结果】:{ComHelper.JsonSerialize(resultProperty?.GetValue(invocation.ReturnValue))}");
            }
            else
            {
                dataIntercept += ($"【执行完成结果】:{invocation.ReturnValue}");
            }

            Parallel.For(0, 1, e =>
            {
                //LogLock.OutSql2Log("AOPLog", new string[] { dataIntercept });
                _logHelper.AopLog($"LogAOP:执行日志:{dataIntercept}");
            });

            //_hubContext.Clients.All.SendAsync("ReceiveUpdate", LogLock.GetLogData()).Wait();
        }