question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

HttpRequestException - An existing connection was forcibly closed by the remote host

See original GitHub issue

We have a web app calling a web service via API calls. We get the below error after creating a new record in that service.

Other code in our application seems to work ok, but for some reason, this particular issue is cropping up for this task only.

System.Net.Http.HttpRequestException HResult=0x80131620 Message=Error while copying content to a stream. Source=System.Net.Http StackTrace: at System.Net.Http.HttpContent.<LoadIntoBufferAsyncCore>d__52.MoveNext() at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Net.Http.HttpClient.<FinishSendAsyncBuffered>d__62.MoveNext() at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() at AcidWebApp.Repositories.LitmusRepository.<CreateLitmus>d__6.MoveNext() in C:\Users\Mark\projects\AcidWebApp\Repositories\LitmusRepository.cs:line 83

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

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

We are using a helper class for this:

using System;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;

namespace AcidWebApp.Helpers
{
    public interface IHttpClientHelper
    {
        Task<HttpClient> GetHttpClient(HttpContext httpContext);
        Task<HttpClient> GetHttpClient();
    }

    public class HttpClientHelper : IHttpClientHelper
    {
        private readonly string _apiUrl;
        private readonly IHttpContextAccessor _httpContextAccessor;

        public HttpClientHelper(string apiUrl, IHttpContextAccessor httpContextAccessor)
        {
            _apiUrl = apiUrl;
            _httpContextAccessor = httpContextAccessor;
        }

        public async Task<HttpClient> GetHttpClient(HttpContext httpContext)
        {
            var client = new HttpClient();
            var accessToken = await httpContext.GetTokenAsync("access_token");
            client.BaseAddress = new Uri(_apiUrl);
            client.SetBearerToken(accessToken);
            return client;
        }

        public async Task<HttpClient> GetHttpClient()
        {
            var client = new HttpClient();
            var accessToken = await _httpContextAccessor.HttpContext.GetTokenAsync("access_token");
            client.BaseAddress = new Uri(_apiUrl);
            client.SetBearerToken(accessToken);
            return client;
        }
    }
}

This is the implementation that has the issue:

public async Task<Litmus> CreateLitmus(Litmus litmus)
{
	var httpClient = await _httpClientHelper.GetHttpClient();
	var response = await httpClient.PostAsJsonAsync("Litmus", litmus);

	if (!response.IsSuccessStatusCode) return null;

	var result = response.Content.ReadAsStringAsync().Result;
	return JsonConvert.DeserializeObject<Litmus>(result);
}

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:6

github_iconTop GitHub Comments

1reaction
dustyghostcommented, Sep 4, 2018

Found the issue, there is a Newtonsoft.Json.JsonSerializationException: Self referencing loop detected this then closes the connection with an unhandled exception.

I know how to resolve that, as it’s our poor data design that is the cause. closing this issue

1reaction
dcarr42commented, Sep 3, 2018

var result = response.Content.ReadAsStringAsync().Result;

That will not play nice when under load.

Read more comments on GitHub >

github_iconTop Results From Across the Web

An existing connection was forcibly closed by the remote host
This generally means that the remote side closed the connection (usually by sending a TCP/IP RST packet).
Read more >
How to solve "An existing connection was forcibly closed ...
The error means the service is not running or the client cannot reach the remote system. You'll want to get the IP address...
Read more >
An existing connection was forcibly closed by the remote ...
We have Azure Function / API which calls On Premise API and we are seeing intermittently SocketException type with below error message -...
Read more >
An existing connection was forcibly closed by the remote host
In this case, when the message says "An existing connection was forcibly closed by the remote host", the connection is closed by the...
Read more >
An existing connection was forcibly closed by the remote host
Solving the error: An existing connection was forcibly closed by the remote host ... This may very well be one of the most...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found