コード例 #1
0
        protected override object Execute(string host, ApiAttribute attr, Hashtable table, Type genericType)
        {
            if (attr == null)
            {
                throw new FubeiSdkException("接口未设置ApiAttribute");
            }
            var appConfig = GalileoApiConfig.Instance.GetApiConfig(attr.Category) ?? new GalileoApiConfig.ApiConfig();

            var param = new ApiRequestParam(attr)
            {
                AppId      = appConfig.AppId,
                VendorSn   = appConfig.VendorSn,
                BizContent = table.ContainsKey(ApiConstants.JsonTag)
                    ? table[ApiConstants.JsonTag].ToString()
                    : JsonConvert.SerializeObject(table, ApiConstants.JsonSerializerSettings)
            };

            var paramList = ConvertToKeyValueList(param, attr);
            // 根据vendorSn是否为空来确定使用AppSecret或者VendorSecret
            var secret = string.IsNullOrEmpty(appConfig.VendorSn) ? appConfig.AppSecret : appConfig.VendorSecret;

            var signature = SignatureGenerator.GetSign(paramList, p => p + secret);

            param.Signature = signature.Signature;
            paramList.Add(new KeyValuePair <string, object>(ApiConstants.Sign, signature.Signature));

            var data = DoRequest(host, attr, paramList);

            // 处理请求
            return(AfterExecution(data, genericType, new RequestCarrier
            {
                Host = host,
                RequestMethod = param.Method
            }));
        }
コード例 #2
0
 public ApiRequestParam(ApiAttribute attr)
 {
     this.Nonce      = RandomStringUtil.NewRandomString(16);
     this.Method     = attr.Method;
     this.SignMethod = attr.SignMethod;
     this.Format     = attr.Format;
     this.Version    = attr.Version;
 }
コード例 #3
0
        private bool IsFormData(string verb, ApiAttribute apiAttr)
        {
            if (verb != HttpMethods.Post && verb != HttpMethods.Put)
            {
                return(false);
            }

            if (apiAttr?.BodyParameter == GenerateBodyParameter.Always ||
                (!DisableAutoDtoInBodyParam && apiAttr?.BodyParameter != GenerateBodyParameter.Never))
            {
                return(false);
            }

            return(true);
        }
コード例 #4
0
        private static IRoutePrefix GetRoutePrefix(Type interfaceType)
        {
            ApiAttribute apiAttribute = interfaceType.GetCustomAttribute <ApiAttribute>();

            if (apiAttribute == null)
            {
                Type element = ((IEnumerable <Type>)interfaceType.GetInterfaces()).FirstOrDefault <Type>();
                apiAttribute = (object)element != null?element.GetCustomAttribute <ApiAttribute>() : (ApiAttribute)null;
            }
            IRoutePrefix routePrefix = (IRoutePrefix)apiAttribute;

            if (routePrefix == null)
            {
                IRoutePrefixAttribute iroutePrefixAttribute = interfaceType.GetCustomAttribute <IRoutePrefixAttribute>();
                if (iroutePrefixAttribute == null)
                {
                    Type element = ((IEnumerable <Type>)interfaceType.GetInterfaces()).FirstOrDefault <Type>();
                    iroutePrefixAttribute = (object)element != null?element.GetCustomAttribute <IRoutePrefixAttribute>() : (IRoutePrefixAttribute)null;
                }
                routePrefix = (IRoutePrefix)iroutePrefixAttribute;
            }
            return(routePrefix);
        }
コード例 #5
0
        private IApiMethodCall ToApiMethodCall(MethodInfo methodInfo, IComponentRegistration apiEntryPointType, ApiAttribute attr, CacheAttribute cache, IEnumerable <ApiCallFilter> filters, List <ApiCallFilter> gloabalFilters)
        {
            var methodCall = Container.Resolve <IApiMethodCall>();

            methodCall.MethodCall            = methodInfo;
            methodCall.Name                  = apiEntryPointType.Services.OfType <KeyedService>().First().ServiceKey.ToString();
            methodCall.ApiClassType          = apiEntryPointType.Activator.LimitType;
            methodCall.HttpMethod            = attr.Method;
            methodCall.RoutingUrl            = ExtractPath(attr.Path);
            methodCall.CacheTime             = cache != null ? cache.CacheTime : 0;
            methodCall.Constraints           = ExtractConstraints(attr.Path, attr.Method);
            methodCall.RequiresAuthorization = attr.RequiresAuthorization;
            methodCall.CheckPayment          = attr.CheckPayment;

            //Add filters
            gloabalFilters.AddRange(filters);
            methodCall.Filters = gloabalFilters;

            return(methodCall);
        }
コード例 #6
0
 protected override OpenApiResponse DoRequest(string host, ApiAttribute attr, List <KeyValuePair <string, object> > paramList)
 {
     return(HttpClientFactory.HttpRequestForOpenApi.PostRequest(host, attr, paramList));
 }
コード例 #7
0
        private IApiMethodCall ToApiMethodCall(MethodInfo methodInfo, ContainerRegistration apiEntryPointType, ApiAttribute attr, CacheAttribute cache, PollAttribute poll, IEnumerable <ApiCallFilter> filters, List <ApiCallFilter> gloabalFilters)
        {
            var methodCall = Container.Resolve <IApiMethodCall>();

            methodCall.MethodCall            = methodInfo;
            methodCall.Name                  = apiEntryPointType.Name;
            methodCall.ApiClassType          = apiEntryPointType.MappedToType;
            methodCall.HttpMethod            = attr.Method;
            methodCall.RoutingUrl            = ExtractPath(attr.Path);
            methodCall.CacheTime             = cache != null ? cache.CacheTime : 0;
            methodCall.Constraints           = ExtractConstraints(attr.Path, attr.Method);
            methodCall.RequiresAuthorization = attr.RequiresAuthorization;
            methodCall.SupportsPoll          = poll != null;
            methodCall.RoutingPollUrl        = poll != null ? poll.PollUrl : string.Empty;

            //Add filters
            gloabalFilters.AddRange(filters);
            methodCall.Filters = gloabalFilters;

            return(methodCall);
        }
コード例 #8
0
        public string PostRequest(string host, ApiAttribute attr, IEnumerable <KeyValuePair <string, object> > paramList)
        {
            // 创建Promise
            Uri uri        = new Uri(host);
            var restClient = new RestClient
            {
                BaseUrl   = uri,
                UserAgent = UserAgentUtil.Instance.FinaleValue
            };

            // 设置WebProxy
            restClient.Proxy = WebProxy;
            // 设置参数
            var request = new RestRequest(attr.Path, Method.POST)
            {
                Timeout = attr.Timeout * 1000
            };

            // 设置请求头
            foreach (var keyValuePair in _customHeaders)
            {
                request.AddHeader(keyValuePair.Key, keyValuePair.Value);
            }

            // 请求的追踪ID,同一个请求和响应的追踪ID是相同的
            var traceId = TraceIdGenerator.NewTraceId();
            var remark  =
                $"HttpClient=RestSharp^TraceId={traceId}^Host={GalileoApiConfig.Instance.LoggerProcMaskHost?.Invoke(host) ?? host}^Method={attr.Method}^Path={attr.Path}";

            switch (attr.Format)
            {
            // json格式,CashierApi/开放平台使用
            case ApiConstants.Json:
            {
                var json = SensitiveKeywordManager.Instance.ReplaceSensitive(AddJsonBody(request, paramList));
                GalileoLogger.Instance.Debug(
                    $"Action=SendRequest^Format=JSON^{remark}^Format=Json^Body={json.Replace("\\\"", "'")}");
                break;
            }

            // 默认Form格式,CashierGw使用
            default:
            {
                var sb = new StringBuilder();
                foreach (var param in paramList)
                {
                    if (param.Value == null)
                    {
                        continue;
                    }
                    request.AddParameter(param.Key, param.Value);
                    if (sb.Length != 0)
                    {
                        sb.Append("&");
                    }

                    sb.Append($"{param.Key}:({param.Value})");
                }

                GalileoLogger.Instance.Debug(
                    $"Action=SendRequest^Format=FORM^{remark}^Format=Form^Body={{{sb}}})");
                break;
            }
            }

            var startTick = Environment.TickCount;
            var response  = restClient.Execute(request);
            var content   = $"{response.Content}";

            if (response.StatusCode != HttpStatusCode.OK)
            {
                content = string.IsNullOrEmpty(response.Content) ? "网络错误,请检查网络连接" : $"网络错误:{response.Content}";
            }

            GalileoLogger.Instance.Debug(
                $"Action=GetResponse^{remark}^Duration={Environment.TickCount - startTick}^StatusCode={response.StatusCode}^Status={response.ResponseStatus}^Body={content}");
            if (response.StatusCode != HttpStatusCode.OK)
            {
                throw new HttpException(Convert.ToInt32(response.StatusCode),
                                        response.StatusDescription, (int)response.ResponseStatus, content, response.ErrorException);
            }
            return(response.Content);
        }
コード例 #9
0
 protected abstract object Execute(string host, ApiAttribute attr, Hashtable table, Type genericType);
コード例 #10
0
 protected abstract T DoRequest(string host, ApiAttribute attr, List <KeyValuePair <string, object> > paramList);