Tuesday, May 29, 2018

Consuming API Using HttpClient

http://www.dotnetcurry.com/aspnet/1192/aspnet-web-api-async-calls-mvc-wpf

 string Baseurl = "https://localhost:223002/";
        public async Task<ActionResult> ApiTEst()
        {
            List<Employee> APIresult = new List<Employee>();
      Employee objEmployee = new Employee ();
            Email= "naveen@gmail.com";
            using (var client = new HttpClient())
            {
                //Passing service base url  
                client.BaseAddress = new Uri(Baseurl);

                client.DefaultRequestHeaders.Clear();
                //Define request data format  
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                //Sending request to find web api REST service resource GetAllEmployees using HttpClient  
  //HttpResponseMessage Res = await client.GetAsync("api/Services/GetEmployee");
      OR
   HttpResponseMessage Res = await client.PostAsJsonAsync("api/MyServices/GetCompleteReleaseData", objEmployee); 

                //Checking the response is successful or not which is sent using HttpClient  
                if (Res.IsSuccessStatusCode)
                {
                    //Storing the response details recieved from web api   
                    var EmpResponse = Res.Content.ReadAsStringAsync().Result;

                    //Deserializing the response recieved from web api and storing into the Employee list  
                    APIresult = JsonConvert.DeserializeObject<List<Employee>>(EmpResponse);

                }
                //returning the employee list to view  
                return View();
            }
        } 
============================================================================================================

    [HttpPost]
        public HttpResponseMessage GetEmployeeData(Employee Email)
        {
            try
            {                
                using (Entities entity = new Entities())
                {                  
                    IEnumerable<Employee> data = entity.GetEmployeeData().ToList();

                    if (data == null)
                    {
                        return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Data is currently not available.");
                    }
                    else
                    {
                        return Request.CreateResponse<IEnumerable<Employee>>(HttpStatusCode.OK, data);
                    }
                }

            }
            catch (Exception)
            {

                throw new Exception("server error");
            }
        }

No comments:

Post a Comment

javascript Filter/index off

 var family = [{"name":"Jack",  "age": 26},               {"name":"Jill",  "age"...