示例#1
0
        protected virtual bool ShouldIntercept(
            IRocketMethodInvocation invocation,
            out AuditLogInfo auditLog,
            out AuditLogActionInfo auditLogAction)
        {
            auditLog       = null;
            auditLogAction = null;

            if (RocketCrossCuttingConcerns.IsApplied(invocation.TargetObject, RocketCrossCuttingConcerns.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 AuthorizeAsync(IRocketMethodInvocation invocation)
 {
     await _methodInvocationAuthorizationService.CheckAsync(
         new MethodInvocationAuthorizationContext (
             invocation.Method
             )
         );
 }
示例#3
0
 protected virtual async Task CheckFeaturesAsync(IRocketMethodInvocation invocation)
 {
     await _methodInvocationFeatureCheckerService.CheckAsync(
         new MethodInvocationFeatureCheckerContext (
             invocation.Method
             )
         );
 }
 /// <summary>
 /// 直接调用方法,并把结果加入缓存
 /// </summary>
 /// <param name="context"></param>
 /// <param name="next"></param>
 /// <param name="key">缓存key</param>
 /// <param name="type">缓存值类型</param>
 /// <returns></returns>
 public async Task GetResultAndSetCache(IRocketMethodInvocation invocation, string cacheKey, long expiration)
 {
     await invocation.ProceedAsync().ContinueWith(task => {
         if (invocation.ReturnValue != null)
         {
             _cache.SetAsync(cacheKey, _serializer.Serialize(invocation.ReturnValue), new DistributedCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromMinutes(expiration)));
         }
     });
 }
示例#5
0
 /// <summary>
 /// 直接调用方法,并把结果加入缓存
 /// </summary>
 /// <param name="context"></param>
 /// <param name="next"></param>
 /// <param name="key">缓存key</param>
 /// <param name="type">缓存值类型</param>
 /// <returns></returns>
 public async Task GetResultAndSetCache(IRocketMethodInvocation invocation, string cacheKey, long expiration)
 {
     await invocation.ProceedAsync().ContinueWith(task => {
         if (invocation.ReturnValue != null)
         {
             _cache.Set(cacheKey, invocation.ReturnValue, TimeSpan.FromMinutes(expiration));
         }
     });
 }
示例#6
0
 protected virtual void Validate(IRocketMethodInvocation invocation)
 {
     _methodInvocationValidator.Validate(
         new MethodInvocationValidationContext(
             invocation.TargetObject,
             invocation.Method,
             invocation.Arguments
             )
         );
 }
示例#7
0
        private async Task <T> MakeRequestAndGetResultAsync <T> (IRocketMethodInvocation invocation)
        {
            var responseAsString = await MakeRequestAsync(invocation);

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

            return(JsonSerializer.Deserialize <T>(responseAsString));
        }
示例#8
0
        public override async Task InterceptAsync(IRocketMethodInvocation invocation)
        {
            if (RocketCrossCuttingConcerns.IsApplied(invocation.TargetObject, RocketCrossCuttingConcerns.FeatureChecking))
            {
                await invocation.ProceedAsync();

                return;
            }

            await CheckFeaturesAsync(invocation);

            await invocation.ProceedAsync();
        }
        public override async Task InterceptAsync(IRocketMethodInvocation invocation)
        {
            var parameters = invocation.Method.GetParameters();

            //判断Method是否包含ref / out参数
            if (parameters.Any(it => it.IsIn || it.IsOut))
            {
                await invocation.ProceedAsync();
            }
            else
            {
                var distributedCacheAttribute = ReflectionHelper.GetSingleAttributeOrDefault <LocalCacheAttribute> (invocation.Method);
                var cacheKey   = CacheKeyHelper.GetCacheKey(invocation.Method, invocation.Arguments, distributedCacheAttribute.Prefix);
                var returnType = invocation.Method.ReturnType.GetGenericArguments().First();
                try {
                    var cacheValue = await _cache.GetAsync(cacheKey);

                    if (cacheValue != null)
                    {
                        var resultValue = _serializer.Deserialize(cacheValue, returnType);
                        invocation.ReturnValue = invocation.IsAsync() ? _taskResultMethod.MakeGenericMethod(returnType).Invoke(null, new object[] { resultValue }) : resultValue;
                    }
                    else
                    {
                        if (!distributedCacheAttribute.ThreadLock)
                        {
                            await GetResultAndSetCache(invocation, cacheKey, distributedCacheAttribute.Expiration);
                        }
                        else
                        {
                            using (await _lock.LockAsync()) {
                                cacheValue = await _cache.GetAsync(cacheKey);

                                if (cacheValue != null)
                                {
                                    var resultValue = _serializer.Deserialize(cacheValue, returnType);
                                    invocation.ReturnValue = invocation.IsAsync() ? _taskResultMethod.MakeGenericMethod(returnType).Invoke(null, new object[] { resultValue }) : resultValue;
                                }
                                else
                                {
                                    await GetResultAndSetCache(invocation, cacheKey, distributedCacheAttribute.Expiration);
                                }
                            }
                        }
                    }
                } catch (Exception) {
                    await invocation.ProceedAsync();
                }
            }
        }
示例#10
0
        public override async Task InterceptAsync(IRocketMethodInvocation 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();
            }
        }
示例#11
0
        private RocketUnitOfWorkOptions CreateOptions(IRocketMethodInvocation invocation, [CanBeNull] UnitOfWorkAttribute unitOfWorkAttribute)
        {
            var options = new RocketUnitOfWorkOptions();

            unitOfWorkAttribute?.SetOptions(options);

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

            return(options);
        }
示例#12
0
        protected virtual void AddHeaders(IRocketMethodInvocation 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(RocketCorrelationIdOptions.HttpHeaderName, CorrelationIdProvider.Get());

            //TenantId
            if (CurrentTenant.Id.HasValue)
            {
                //TODO: Use RocketAspNetCoreMultiTenancyOptions 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");
        }
示例#13
0
        public override async Task InterceptAsync(IRocketMethodInvocation 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]
                    );
            }
        }
示例#14
0
        public override async Task InterceptAsync(IRocketMethodInvocation 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);
            }
        }
示例#15
0
        private async Task <string> MakeRequestAsync(IRocketMethodInvocation invocation)
        {
            var clientConfig = ClientOptions.HttpClientProxies.GetOrDefault(typeof(TService)) ??
                               throw new RocketException($"Could not get DynamicHttpClientProxyConfig for {typeof(TService).FullName}.");
            var remoteServiceConfig = RocketRemoteServiceOptions.RemoteServices.GetConfigurationOrDefault(clientConfig.RemoteServiceName);

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

            var action = await ApiDescriptionFinder.FindActionAsync(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());
        }
示例#16
0
 public abstract Task InterceptAsync(IRocketMethodInvocation invocation);
示例#17
0
        public override async Task InterceptAsync(IRocketMethodInvocation invocation)
        {
            await AuthorizeAsync(invocation);

            await invocation.ProceedAsync();
        }
示例#18
0
 public override async Task InterceptAsync(IRocketMethodInvocation invocation)
 {
     Validate(invocation);
     await invocation.ProceedAsync();
 }