示例#1
0
        public override async Task InterceptAsync(IPlusMethodInvocation invocation)
        {
            if (!ShouldIntercept(invocation, out var auditLog, out var auditLogAction))
            {
                await invocation.ProceedAsync();

                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);
            }
        }
示例#2
0
        protected virtual bool ShouldIntercept(
            IPlusMethodInvocation invocation,
            out AuditLogInfo auditLog,
            out AuditLogActionInfo auditLogAction)
        {
            auditLog       = null;
            auditLogAction = null;

            if (PlusCrossCuttingConcerns.IsApplied(invocation.TargetObject, PlusCrossCuttingConcerns.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);
        }
 protected virtual async Task CheckFeaturesAsync(IPlusMethodInvocation invocation)
 {
     await _methodInvocationFeatureCheckerService.CheckAsync(
         new MethodInvocationFeatureCheckerContext(
             invocation.Method
             )
         );
 }
 protected virtual async Task AuthorizeAsync(IPlusMethodInvocation invocation)
 {
     await _methodInvocationAuthorizationService.CheckAsync(
         new MethodInvocationAuthorizationContext(
             invocation.Method
             )
         );
 }
示例#5
0
 protected virtual void Validate(IPlusMethodInvocation invocation)
 {
     _methodInvocationValidator.Validate(
         new MethodInvocationValidationContext(
             invocation.TargetObject,
             invocation.Method,
             invocation.Arguments
             )
         );
 }
示例#6
0
        private async Task <T> MakeRequestAndGetResultAsync <T>(IPlusMethodInvocation invocation)
        {
            var responseAsString = await MakeRequestAsync(invocation);

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

            return(JsonSerializer.Deserialize <T>(responseAsString));
        }
        public override async Task InterceptAsync(IPlusMethodInvocation invocation)
        {
            if (PlusCrossCuttingConcerns.IsApplied(invocation.TargetObject, PlusCrossCuttingConcerns.FeatureChecking))
            {
                await invocation.ProceedAsync();

                return;
            }

            await CheckFeaturesAsync(invocation);

            await invocation.ProceedAsync();
        }
        private PlusUnitOfWorkOptions CreateOptions(IPlusMethodInvocation invocation, [CanBeNull] UnitOfWorkAttribute unitOfWorkAttribute)
        {
            var options = new PlusUnitOfWorkOptions();

            unitOfWorkAttribute?.SetOptions(options);

            if (unitOfWorkAttribute?.IsTransactional == null)
            {
                options.IsTransactional = _defaultOptions.CalculateIsTransactional(
                    autoValue: !invocation.Method.Name.StartsWith("Get", StringComparison.InvariantCultureIgnoreCase)
                    );
            }

            return(options);
        }
        public override async Task InterceptAsync(IPlusMethodInvocation invocation)
        {
            if (!UnitOfWorkHelper.IsUnitOfWorkMethod(invocation.Method, out var unitOfWorkAttribute))
            {
                await invocation.ProceedAsync();

                return;
            }

            using (var uow = _unitOfWorkManager.Begin(CreateOptions(invocation, unitOfWorkAttribute)))
            {
                await invocation.ProceedAsync();

                await uow.CompleteAsync();
            }
        }
示例#10
0
        protected virtual void AddHeaders(IPlusMethodInvocation 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(PlusCorrelationIdOptions.HttpHeaderName, CorrelationIdProvider.Get());

            //TenantId
            if (CurrentTenant.Id.HasValue)
            {
                //TODO: Use PlusAspNetCoreMultiTenancyOptions to get the key
                requestMessage.Headers.Add(TenantResolverConsts.DefaultTenantKey, CurrentTenant.Id.Value.ToString());
            }

            //Culture
            //TODO: Is that the way we want? Couldn't send the culture (not ui culture)
            var currentCulture = CultureInfo.CurrentUICulture.Name ?? CultureInfo.CurrentCulture.Name;

            if (!currentCulture.IsNullOrEmpty())
            {
                requestMessage.Headers.AcceptLanguage.Add(new StringWithQualityHeaderValue(currentCulture));
            }

            //X-Requested-With
            requestMessage.Headers.Add("X-Requested-With", "XMLHttpRequest");
        }
示例#11
0
        public override async Task InterceptAsync(IPlusMethodInvocation invocation)
        {
            if (invocation.Method.ReturnType.GenericTypeArguments.IsNullOrEmpty())
            {
                await MakeRequestAsync(invocation);
            }
            else
            {
                var result = (Task)GenericInterceptAsyncMethod
                             .MakeGenericMethod(invocation.Method.ReturnType.GenericTypeArguments[0])
                             .Invoke(this, new object[] { invocation });

                invocation.ReturnValue = await GetResultAsync(
                    result,
                    invocation.Method.ReturnType.GetGenericArguments()[0]
                    );
            }
        }
示例#12
0
        private async Task <string> MakeRequestAsync(IPlusMethodInvocation invocation)
        {
            var clientConfig        = ClientOptions.HttpClientProxies.GetOrDefault(typeof(TService)) ?? throw new PlusException($"Could not get DynamicHttpClientProxyConfig for {typeof(TService).FullName}.");
            var remoteServiceConfig = PlusRemoteServiceOptions.RemoteServices.GetConfigurationOrDefault(clientConfig.RemoteServiceName);

            var client = HttpClientFactory.Create(clientConfig.RemoteServiceName);

            var action = await ApiDescriptionFinder.FindActionAsync(client, remoteServiceConfig.BaseUrl, typeof(TService), invocation.Method);

            var apiVersion = GetApiVersionInfo(action);
            var url        = remoteServiceConfig.BaseUrl.EnsureEndsWith('/') + 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);

            await ClientAuthenticator.AuthenticateAsync(
                new RemoteServiceHttpClientAuthenticateContext(
                    client,
                    requestMessage,
                    remoteServiceConfig,
                    clientConfig.RemoteServiceName
                    )
                );

            var response = await client.SendAsync(requestMessage, GetCancellationToken());

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

            return(await response.Content.ReadAsStringAsync());
        }
        public override async Task InterceptAsync(IPlusMethodInvocation invocation)
        {
            await AuthorizeAsync(invocation);

            await invocation.ProceedAsync();
        }
示例#14
0
 public override async Task InterceptAsync(IPlusMethodInvocation invocation)
 {
     Validate(invocation);
     await invocation.ProceedAsync();
 }
示例#15
0
 public abstract Task InterceptAsync(IPlusMethodInvocation invocation);