Saturday, January 23, 2016

Reading WebAPI from MVC Controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataModel.Models;
using System.Net.Http;

namespace MOACommons.HttpMethods
{
    public static class WebAPIHelper
    {
        #region Common Function


        public static dynamic GetWebAPIService(string serviceUrl)
        {
            dynamic dataResponse = null;

            using (HttpClient httpClient = new HttpClient())
            {

                httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                System.Net.Http.HttpResponseMessage response = httpClient.GetAsync(serviceUrl).Result;
               // response = httpClient.GetAsync(serviceUrl).Result;
                if (response.IsSuccessStatusCode)
                {
                    var rslt = response.Content.ReadAsStringAsync();
                    dataResponse = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(rslt.Result);
                   return dataResponse;
               // return response;
                }
                else
                {
                    dataResponse = "-34";//"Failed to call service";
                    return dataResponse;
                }
                //return dataResponse;
            }

        }


        public static dynamic PostWebAPIService(string serviceUrl, object ObjectToPost)
        {
            HttpClient httpClient = new HttpClient();
            dynamic dataResponse = null;
            httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
            HttpResponseMessage response = httpClient.PostAsJsonAsync(serviceUrl, ObjectToPost).Result;


            if (response.IsSuccessStatusCode)
            {
                var rslt = response.Content.ReadAsStringAsync();
                dataResponse = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(rslt.Result);
                return dataResponse;
            }
            else
            {
                dataResponse = "-34";//"Failed to call service";
                return dataResponse;
            }


        }

        #endregion
    }
}

No comments:

Post a Comment