コード例 #1
0
        public override async Task InterceptAsync(IAbpMethodInvocation invocation)
        {
            using (var serviceScope = _serviceScopeFactory.CreateScope())
            {
                var auditingHelper  = serviceScope.ServiceProvider.GetRequiredService <IAuditingHelper>();
                var auditingOptions = serviceScope.ServiceProvider.GetRequiredService <IOptions <AbpAuditingOptions> >().Value;

                if (!ShouldIntercept(invocation, auditingOptions, auditingHelper))
                {
                    await invocation.ProceedAsync();

                    return;
                }

                var auditingManager = serviceScope.ServiceProvider.GetRequiredService <IAuditingManager>();
                if (auditingManager.Current != null)
                {
                    await ProceedByLoggingAsync(invocation, auditingHelper, auditingManager.Current);
                }
                else
                {
                    var currentUser = serviceScope.ServiceProvider.GetRequiredService <ICurrentUser>();
                    await ProcessWithNewAuditingScopeAsync(invocation, auditingOptions, currentUser, auditingManager, auditingHelper);
                }
            }
        }
コード例 #2
0
        protected virtual bool ShouldIntercept(
            IAbpMethodInvocation invocation,
            out AuditLogInfo auditLog,
            out AuditLogActionInfo auditLogAction)
        {
            auditLog       = null;
            auditLogAction = null;

            if (AbpCrossCuttingConcerns.IsApplied(invocation.TargetObject, AbpCrossCuttingConcerns.Auditing))
            {
                return(false);
            }

            var auditLogScope = _auditingManager.Current;

            if (auditLogScope == null)
            {
                return(false);
            }

            if (!_auditingHelper.ShouldSaveAudit(invocation.Method))
            {
                return(false);
            }

            auditLog       = auditLogScope.Log;
            auditLogAction = _auditingHelper.CreateAuditLogAction(
                auditLog,
                invocation.TargetObject.GetType(),
                invocation.Method,
                invocation.Arguments
                );

            return(true);
        }
コード例 #3
0
        private async Task <T> MakeRequestAndGetResultAsync <T>(IAbpMethodInvocation invocation)
        {
            var responseContent = await MakeRequestAsync(invocation);

            if (typeof(T) == typeof(IRemoteStreamContent))
            {
                /* returning a class that holds a reference to response
                * content just to be sure that GC does not dispose of
                * it before we finish doing our work with the stream */
                return((T)(object)new RemoteStreamContent(await responseContent.ReadAsStreamAsync())
                {
                    ContentType = responseContent.Headers.ContentType?.ToString()
                });
            }

            var stringContent = await responseContent.ReadAsStringAsync();

            if (typeof(T) == typeof(string))
            {
                return((T)(object)stringContent);
            }

            if (stringContent.IsNullOrWhiteSpace())
            {
                return(default);
コード例 #4
0
        private async Task <string> MakeRequest(IAbpMethodInvocation invocation)
        {
            using (var client = _httpClientFactory.Create())
            {
                var baseUrl = GetBaseUrl();
                var action  = await _apiDescriptionFinder.FindActionAsync(baseUrl, typeof(TService), invocation.Method);

                var apiVersion = GetApiVersionInfo(action);
                var url        = baseUrl + UrlBuilder.GenerateUrlWithParameters(action, invocation.ArgumentsDictionary, apiVersion);

                var requestMessage = new HttpRequestMessage(action.GetHttpMethod(), url)
                {
                    Content = RequestPayloadBuilder.BuildContent(action, invocation.ArgumentsDictionary, _jsonSerializer, apiVersion)
                };

                AddHeaders(invocation, action, requestMessage, apiVersion);

                var response = await client.SendAsync(requestMessage);

                if (!response.IsSuccessStatusCode)
                {
                    await ThrowExceptionForResponseAsync(response);
                }

                return(await response.Content.ReadAsStringAsync());
            }
        }
コード例 #5
0
        protected virtual void AddHeaders(IAbpMethodInvocation invocation, ActionApiDescriptionModel action, HttpRequestMessage requestMessage, ApiVersionInfo apiVersion)
        {
            //API Version
            if (!apiVersion.Version.IsNullOrEmpty())
            {
                //TODO: What about other media types?
                requestMessage.Headers.Add("accept", $"{MimeTypes.Text.Plain}; v={apiVersion.Version}");
                requestMessage.Headers.Add("accept", $"{MimeTypes.Application.Json}; v={apiVersion.Version}");
                requestMessage.Headers.Add("api-version", apiVersion.Version);
            }

            //Header parameters
            var headers = action.Parameters.Where(p => p.BindingSourceId == ParameterBindingSources.Header).ToArray();

            foreach (var headerParameter in headers)
            {
                var value = HttpActionParameterHelper.FindParameterValue(invocation.ArgumentsDictionary, headerParameter);
                if (value != null)
                {
                    requestMessage.Headers.Add(headerParameter.Name, value.ToString());
                }
            }

            //CorrelationId
            requestMessage.Headers.Add(CorrelationIdOptions.HttpHeaderName, CorrelationIdProvider.Get());
        }
コード例 #6
0
        private async Task ProcessWithNewAuditingScopeAsync(
            IAbpMethodInvocation invocation,
            AbpAuditingOptions options,
            ICurrentUser currentUser,
            IAuditingManager auditingManager,
            IAuditingHelper auditingHelper)
        {
            var hasError = false;

            using (var saveHandle = auditingManager.BeginScope())
            {
                try
                {
                    await ProceedByLoggingAsync(invocation, auditingHelper, auditingManager.Current);

                    Debug.Assert(auditingManager.Current != null);
                    if (auditingManager.Current.Log.Exceptions.Any())
                    {
                        hasError = true;
                    }
                }
                catch (Exception)
                {
                    hasError = true;
                    throw;
                }
                finally
                {
                    if (ShouldWriteAuditLog(invocation, options, currentUser, hasError))
                    {
                        await saveHandle.SaveAsync();
                    }
                }
            }
        }
コード例 #7
0
        public override async Task InterceptAsync(IAbpMethodInvocation invocation)
        {
            Console.WriteLine("in the aloha interceptor");
            await invocation.ProceedAsync();

            Console.WriteLine("out of aloha interceptor");
        }
コード例 #8
0
        public override async Task InterceptAsync(IAbpMethodInvocation invocation)
        {
            if (!UnitOfWorkHelper.IsUnitOfWorkMethod(invocation.Method, out var unitOfWorkAttribute))
            {
                await invocation.ProceedAsync();

                return;
            }

            var options = CreateOptions(invocation, unitOfWorkAttribute);

            //Trying to begin a reserved UOW by AbpUnitOfWorkMiddleware
            if (_unitOfWorkManager.TryBeginReserved(UnitOfWork.UnitOfWorkReservationName, options))
            {
                await invocation.ProceedAsync();

                return;
            }

            using (var uow = _unitOfWorkManager.Begin(options))
            {
                await invocation.ProceedAsync();

                await uow.CompleteAsync();
            }
        }
コード例 #9
0
        public override async Task InterceptAsync(IAbpMethodInvocation invocation)
        {
            if (!ShouldIntercept(invocation, out var auditLog, out var auditLogAction))
            {
                invocation.Proceed();
                return;
            }

            var stopwatch = Stopwatch.StartNew();

            try
            {
                await invocation.ProceedAsync();
            }
            catch (Exception ex)
            {
                auditLog.Exceptions.Add(ex);
                throw;
            }
            finally
            {
                stopwatch.Stop();
                auditLogAction.ExecutionDuration = Convert.ToInt32(stopwatch.Elapsed.TotalMilliseconds);
                auditLog.Actions.Add(auditLogAction);
            }
        }
コード例 #10
0
        public override async Task InterceptAsync(IAbpMethodInvocation invocation)
        {
            if (!UnitOfWorkHelper.IsUnitOfWorkMethod(invocation.Method, out var unitOfWorkAttribute))
            {
                await invocation.ProceedAsync();

                return;
            }

            using (var scope = _serviceScopeFactory.CreateScope())
            {
                var options = CreateOptions(scope.ServiceProvider, invocation, unitOfWorkAttribute);

                var unitOfWorkManager = scope.ServiceProvider.GetRequiredService <IUnitOfWorkManager>();

                //Trying to begin a reserved UOW by AbpUnitOfWorkMiddleware
                if (unitOfWorkManager.TryBeginReserved(UnitOfWork.UnitOfWorkReservationName, options))
                {
                    await invocation.ProceedAsync();

                    return;
                }

                using (var uow = unitOfWorkManager.Begin(options))
                {
                    await invocation.ProceedAsync();

                    await uow.CompleteAsync();
                }
            }
        }
        private async Task MakeRequestAsync(IAbpMethodInvocation invocation)
        {
            // 获取Actor配置
            var actorProxyConfig    = DaprActorProxyOptions.ActorProxies.GetOrDefault(typeof(TService)) ?? throw new AbpException($"Could not get DynamicDaprActorProxyConfig for {typeof(TService).FullName}.");
            var remoteServiceConfig = DaprActorOptions.RemoteActors.GetConfigurationOrDefault(actorProxyConfig.RemoteServiceName);

            var actorProxyOptions = new ActorProxyOptions
            {
                HttpEndpoint = remoteServiceConfig.BaseUrl
            };

            // 自定义请求处理器
            // 添加请求头用于传递状态
            // TODO: Actor一次只能处理一个请求,使用状态管理来传递状态的可行性?
            var httpClientHandler = new DaprHttpClientHandler();

            // 身份认证处理
            await ActoryProxyAuthenticator.AuthenticateAsync(
                new DaprActorProxyAuthenticateContext(
                    httpClientHandler, remoteServiceConfig, actorProxyConfig.RemoteServiceName));

            AddHeaders(httpClientHandler);

            // 代理工厂
            var proxyFactory = new ActorProxyFactory(actorProxyOptions, (HttpMessageHandler)httpClientHandler);

            await MakeRequestAsync(invocation, proxyFactory, remoteServiceConfig);
        }
コード例 #12
0
    private async Task <bool> ShouldWriteAuditLogAsync(
        IAbpMethodInvocation invocation,
        AuditLogInfo auditLogInfo,
        AbpAuditingOptions options,
        ICurrentUser currentUser,
        bool hasError)
    {
        foreach (var selector in options.AlwaysLogSelectors)
        {
            if (await selector(auditLogInfo))
            {
                return(true);
            }
        }

        if (options.AlwaysLogOnException && hasError)
        {
            return(true);
        }

        if (!options.IsEnabledForAnonymousUsers && !currentUser.IsAuthenticated)
        {
            return(false);
        }

        if (!options.IsEnabledForGetRequests &&
            invocation.Method.Name.StartsWith("Get", StringComparison.OrdinalIgnoreCase))
        {
            return(false);
        }

        return(true);
    }
コード例 #13
0
        private static async Task ProceedByLoggingAsync(
            IAbpMethodInvocation invocation,
            IAuditingHelper auditingHelper,
            IAuditLogScope auditLogScope)
        {
            var auditLog       = auditLogScope.Log;
            var auditLogAction = auditingHelper.CreateAuditLogAction(
                auditLog,
                invocation.TargetObject.GetType(),
                invocation.Method,
                invocation.Arguments
                );

            var stopwatch = Stopwatch.StartNew();

            try
            {
                await invocation.ProceedAsync();
            }
            catch (Exception ex)
            {
                auditLog.Exceptions.Add(ex);
                throw;
            }
            finally
            {
                stopwatch.Stop();
                auditLogAction.ExecutionDuration = Convert.ToInt32(stopwatch.Elapsed.TotalMilliseconds);
                auditLog.Actions.Add(auditLogAction);
            }
        }
コード例 #14
0
 protected virtual Task AuthorizeAsync(IAbpMethodInvocation invocation)
 {
     return(_methodInvocationAuthorizationService.CheckAsync(
                new MethodInvocationAuthorizationContext(
                    invocation.Method
                    )
                ));
 }
コード例 #15
0
ファイル: AuthorizationInterceptor.cs プロジェクト: zxbe/abp
 protected virtual async Task AuthorizeAsync(IAbpMethodInvocation invocation)
 {
     await _methodInvocationAuthorizationService.CheckAsync(
         new MethodInvocationAuthorizationContext(
             invocation.Method
             )
         ).ConfigureAwait(false);
 }
コード例 #16
0
        public override async Task InterceptAsync(IAbpMethodInvocation invocation)
        {
            _logger.LogTrace($"{invocation.Method.Name} Executing ...");

            await invocation.ProceedAsync();

            _logger.LogTrace($"{invocation.Method.Name} Executed ...");
        }
コード例 #17
0
 protected virtual Task CheckFeaturesAsync(IAbpMethodInvocation invocation)
 {
     return(_methodInvocationFeatureCheckerService.CheckAsync(
                new MethodInvocationFeatureCheckerContext(
                    invocation.Method
                    )
                ));
 }
コード例 #18
0
 public override void Intercept(IAbpMethodInvocation invocation)
 {
     invocation.ReturnValue = _cache.GetOrAdd(invocation.Method, m =>
     {
         invocation.Proceed();
         return(invocation.ReturnValue);
     });
 }
コード例 #19
0
 protected virtual async Task CheckFeaturesAsync(IAbpMethodInvocation invocation)
 {
     await _methodInvocationFeatureCheckerService.CheckAsync(
         new MethodInvocationFeatureCheckerContext(
             invocation.Method
             )
         ).ConfigureAwait(false);
 }
コード例 #20
0
        public override async Task InterceptAsync(IAbpMethodInvocation invocation)
        {
            //await Task.Delay(5); CAN NOT USE await before method execution! This is a restriction of Castle DynamicProxy
            (invocation.TargetObject as ICanLogOnObject)?.Logs?.Add($"{GetType().Name}_InterceptAsync_BeforeInvocation");
            await invocation.ProceedAsync();

            (invocation.TargetObject as ICanLogOnObject)?.Logs?.Add($"{GetType().Name}_InterceptAsync_AfterInvocation");
            await Task.Delay(5);
        }
コード例 #21
0
        public override async Task InterceptAsync(IAbpMethodInvocation invocation)
        {
            var profiler = StackExchange.Profiling.MiniProfiler.Current;

            using (profiler.Step(invocation.Method.Name))
            {
                // Do some work...
                await invocation.ProceedAsync();
            }
        }
コード例 #22
0
    public override async Task InterceptAsync(IAbpMethodInvocation invocation)
    {
        await Task.Delay(5);

        (invocation.TargetObject as ICanLogOnObject)?.Logs?.Add($"{GetType().Name}_InterceptAsync_BeforeInvocation");
        await invocation.ProceedAsync();

        (invocation.TargetObject as ICanLogOnObject)?.Logs?.Add($"{GetType().Name}_InterceptAsync_AfterInvocation");
        await Task.Delay(5);
    }
コード例 #23
0
ファイル: ValidationInterceptor.cs プロジェクト: leen2175/abp
 protected virtual void Validate(IAbpMethodInvocation invocation)
 {
     _validator.Validate(
         new MethodInvocationValidationContext(
             invocation.TargetObject,
             invocation.Method,
             invocation.Arguments
             )
         );
 }
コード例 #24
0
 protected virtual async Task ValidateAsync(IAbpMethodInvocation invocation)
 {
     await _methodInvocationValidator.ValidateAsync(
         new MethodInvocationValidationContext(
             invocation.TargetObject,
             invocation.Method,
             invocation.Arguments
             )
         );
 }
コード例 #25
0
        public override void Intercept(IAbpMethodInvocation invocation)
        {
            if (AbpCrossCuttingConcerns.IsApplied(invocation.TargetObject, AbpCrossCuttingConcerns.Authorization))
            {
                invocation.Proceed();
                return;
            }

            AsyncHelper.RunSync(() => AuthorizeAsync(invocation));
            invocation.Proceed();
        }
コード例 #26
0
 protected virtual async Task CheckFeaturesAsync(IAbpMethodInvocation invocation)
 {
     using (var scope = _serviceScopeFactory.CreateScope())
     {
         await scope.ServiceProvider.GetRequiredService <IMethodInvocationFeatureCheckerService>().CheckAsync(
             new MethodInvocationFeatureCheckerContext(
                 invocation.Method
                 )
             );
     }
 }
コード例 #27
0
        private async Task <T> MakeRequestAndGetResultAsync <T>(IAbpMethodInvocation invocation)
        {
            var responseAsString = await MakeRequestAsync(invocation);

            if (typeof(T) == typeof(string))
            {
                return((T)Convert.ChangeType(responseAsString, typeof(T)));
            }

            return(JsonSerializer.Deserialize <T>(responseAsString));
        }
コード例 #28
0
        private async Task <T> MakeRequestAndGetResultAsync <T>(IAbpMethodInvocation invocation)
        {
            var responseAsString = await MakeRequest(invocation);

            //TODO: Think on that
            if (TypeHelper.IsPrimitiveExtended(typeof(T), true))
            {
                return((T)Convert.ChangeType(responseAsString, typeof(T)));
            }

            return(_jsonSerializer.Deserialize <T>(responseAsString));
        }
コード例 #29
0
    public override async Task InterceptAsync(IAbpMethodInvocation invocation)
    {
        if (_cache.ContainsKey(invocation.Method))
        {
            invocation.ReturnValue = _cache[invocation.Method];
            return;
        }

        await invocation.ProceedAsync();

        _cache[invocation.Method] = invocation.ReturnValue;
    }
コード例 #30
0
ファイル: ValidationInterceptor.cs プロジェクト: leen2175/abp
        public override void Intercept(IAbpMethodInvocation invocation)
        {
            if (AbpCrossCuttingConcerns.IsApplied(invocation.TargetObject, AbpCrossCuttingConcerns.Validation))
            {
                invocation.Proceed();
                return;
            }

            Validate(invocation);

            invocation.Proceed();
        }