예제 #1
0
        /// <summary>
        /// Send request to service and getting result
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="serviceUrl"></param>
        /// <param name="authorizeCode"></param>
        /// <param name="apiAction"></param>
        /// <param name="method"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static T SendApiRequest <T>(string serviceUrl, string authorizeCode, string apiAction, HttpMethod method,
                                           RouteValueDictionary parameters)
        {
            var client = new HttpClient
            {
                BaseAddress = new Uri(serviceUrl)
            };

            if (!string.IsNullOrEmpty(authorizeCode))
            {
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
                                                                                           Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(authorizeCode)));
            }

            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage responseMessage;

            if (method == HttpMethod.Post)
            {
                responseMessage = client.PostAsJsonAsync(apiAction, parameters).Result;
            }
            else
            {
                var url = UrlUtilities.CombineQueryString(apiAction, parameters);
                responseMessage = client.GetAsync(url).Result;
            }

            var result = responseMessage.Content.ReadAsAsync <T>().Result;

            return(result);
        }