0

This is my first time when I am trying to consume the web api in asp.net web application.

I have a web api get method which accepts one parameter. I am trying to consume that method in my asp.net web application (in default.aspx.cs) something like below.

        var url = "api/GetLeaveTypes?ID=00013159";           
        using (HttpClient client = new HttpClient())
        {
            HttpResponseMessage responseMessage = null;
            responseMessage = client.GetAsync(url).Result;
            responseMessage.EnsureSuccessStatusCode();
            string responJsonText = responseMessage.Content.ReadAsStringAsync().Result;
            var result = (new JavaScriptSerializer()).DeserializeObject(responJsonText);
        }

I am getting error like

HttpRequestException: An error occurred while sending the request.

WebException: The underlying connection was closed: An unexpected error occurred on a send.

IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.

SocketException: An existing connection was forcibly closed by the remote host

Rocky
  • 4,454
  • 14
  • 64
  • 119
  • What version of the .NET Framework are you using? Also note that your HttpClient usage is incorrect. See [You're Using HttpClient Wrong And It's Destablizing Your Software](https://www.aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/). I recommend using [Flurl](https://flurl.dev/) instead of HttpClient. It's not the cause of your current exception, but it is something you need to fix. – mason Jan 12 '21 at 20:52
  • I am using .NET Framework 4.5.2 – Rocky Jan 12 '21 at 20:54
  • I tried to use method from this https://www.tutorialsteacher.com/webapi/consuming-web-api-in-dotnet-using-httpclient but getting same exception – Rocky Jan 12 '21 at 20:55
  • That tutorial is demonstrating some very bad practices. I would avoid that tutorial if I were you. – mason Jan 12 '21 at 20:59
  • By default. .NET 4.5.2 doesn't enable TLS 1.2. That's one possible source of that error message. Check [this answer](https://stackoverflow.com/a/45692875/1139830) for an explanation and solution. I highly recommend updating to the latest .NET Framework version so that you get the latest bug fixes and can take advantage of newer improvements, and you won't have to do workarounds for TLS 1.2 – mason Jan 12 '21 at 21:06
  • I upgraded the .NET Framework to 4.7.2 then also I am getting same exceptions – Rocky Jan 13 '21 at 02:31
  • What happens if you use an absolute path to the API, such as `https://example.com/api/GetLeaveTypes?ID=00013159`? – mason Jan 13 '21 at 13:45
  • in browser am able to see the result but at the same time when calling this from VS2017, getting exception – Rocky Jan 13 '21 at 16:03

0 Answers0