Beispiel #1
0
        private (MethodInfo, Expression[]) GetApiMethodAndParameters(
            string methodName,
            HttpMethod httpMethod,
            IEnumerable <string> argsNames,
            Expression[] argsValues)
        {
            // Setup query string for simple args and body for one complex arg.
            var    queryDict  = new Dictionary <string, string>();
            string bodyString = null;

            for (int i = 0; i < argsNames.Count(); i++)
            {
                var constValue  = ReduceToConstant(argsValues[i]);
                var typeOfValue = constValue.GetType();
                var stringValue = objectConverter.ConvertToString(constValue);

                if (TypeHelpers.IsSimpleType(typeOfValue))
                {
                    queryDict.Add(argsNames.ElementAt(i), stringValue);
                }
                else if (string.IsNullOrEmpty(bodyString))
                {
                    bodyString = stringValue;
                }
                else
                {
                    throw new ArgumentException("Only one argument can be complex type.");
                }
            }

            // Create url with query args.
            var url = methodName + queryDict.Aggregate("?", (s, kvp) => $"{s}{kvp.Key}={kvp.Value}&");

            // Construct HttpRequestMessage.
            var httpRequestMessageConstructor = typeof(HttpRequestMessage)
                                                .GetConstructor(new[] { typeof(HttpMethod), typeof(string) });
            var httpRequestMessageCtorExpression = Expression.New(
                httpRequestMessageConstructor,
                Expression.Constant(httpMethod),
                Expression.Constant(url));

            // Add prop initializer with Content initialize if needs.
            Expression httpRequestMessage = httpRequestMessageCtorExpression;

            if (httpMethod != HttpMethod.Get && httpMethod != HttpMethod.Head && bodyString != null)
            {
                httpRequestMessage = SetupContentPropertyInitializer(
                    httpRequestMessageCtorExpression,
                    GetBodyContentExpression(bodyString));
            }

            var parameters = new[] { httpRequestMessage };
            var apiMethod  = typeof(HttpClient).GetMethod(SendAsyncMethodName, new[] { typeof(HttpRequestMessage) });

            return(apiMethod, parameters);
        }