Link to home
Start Free TrialLog in
Avatar of dodgerfan
dodgerfanFlag for United States of America

asked on

Getting an unhandled exception error when trying to call an api from an ASP.Net Core web app

I have an ASP.Net Core 2.0 web application that calls a Web API in a different project. When I try to run it I get the error An unhandled exception occurred while processing the request. Further detail leads to this: WinHttpException: A connection with the server could not be established. I have not run into this yet. The code for the controller is below. It erros out on this line:
HttpResponseMessage Res = await client.GetAsync("api/players");

Open in new window


Here is my HomeController.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using MyAPIClient.Models;
using Newtonsoft.Json;

namespace MyAPIClient.Controllers
{
    public class HomeController : Controller
    {
        string Baseurl = "http://localhost:60000/";
        public async Task<ActionResult> Index()
        {
            List<Player> PlayerInfo = new List<Player>();

            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 GetAllPlayers using HttpClient  
                HttpResponseMessage Res = await client.GetAsync("api/players");

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

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

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

        [HttpPost]
        public async Task<ActionResult> Search(string searchterm)
        {
            List<Player> PlayerInfo = new List<Player>();
            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 GetAllPlayers using HttpClient  
                HttpResponseMessage Res = await client.GetAsync("api/players/find/" + searchterm);

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

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

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

        public async Task<ActionResult> Search()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Edit(int StudentId)
        {
            List<Player> PlayerInfo = new List<Player>();

            //Get the student from studentList sample collection for demo purpose.
            //You can get the student from the database in the real application
            var std = PlayerInfo.Where(s => s.ID == StudentId).FirstOrDefault();

            return View(std);
        }
    }
}

Open in new window

Any help is appreciated.
ASKER CERTIFIED SOLUTION
Avatar of Ryan Chong
Ryan Chong
Flag of Singapore image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial