'Web API: Error when calling responseTask.Wait() after GetAsync in ActionResult
I am following a Web API tutorial, everything has been fine, but I am getting an 'SocketException: An existing connection was forcibly closed by the remote host' exception in the responseTask.Wait() call.
public class StudentController : Controller
{
public ActionResult Index()
{
IEnumerable<StudentViewModel> students = null;
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:64189/api/");
var responseTask = client.GetAsync("student");
responseTask.Wait();
var result = responseTask.Result;
if (result.IsSuccessStatusCode)
{
var readTask = result.Content.ReadAsAsync<IList<StudentViewModel>>();
readTask.Wait();
students = readTask.Result;
}
else
{
students = Enumerable.Empty<StudentViewModel>();
ModelState.AddModelError(string.Empty, "Server error. Please contact administrator.");
}
}
return View(students);
}
}
I already add a ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 but it didn't solve anything.
I tested the API itself https://localhost:12345/api/student and the service is Ok. It's in the responseTask.Wait method where it fails.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
