aspnetcore icon indicating copy to clipboard operation
aspnetcore copied to clipboard

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

Open dustyghost opened this issue 8 years ago • 6 comments

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.d__52.MoveNext() at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Net.Http.HttpClient.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.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);
}

dustyghost avatar Sep 03 '18 12:09 dustyghost

System info:

Microsoft Visual Studio Professional 2017 Version 15.7.4 VisualStudio.15.Release/15.7.4+27703.2035 Microsoft .NET Framework Version 4.7.03056

Installed Version: Professional

Application Insights Tools for Visual Studio Package 8.12.10405.1 Application Insights Tools for Visual Studio

ASP.NET and Web Tools 2017 15.0.40601.0 ASP.NET and Web Tools 2017

ASP.NET Core Razor Language Services 15.7.31476 Provides languages services for ASP.NET Core Razor.

ASP.NET Web Frameworks and Tools 2017 5.2.60419.0 For additional information, visit https://www.asp.net/

Azure App Service Tools v3.0.0 15.0.40608.0 Azure App Service Tools v3.0.0

Azure Data Lake Node 1.0 This package contains the Data Lake integration nodes for Server Explorer.

Azure Data Lake Tools for Visual Studio 2.3.3000.2 Microsoft Azure Data Lake Tools for Visual Studio

Azure Functions and Web Jobs Tools 15.0.40608.0 Azure Functions and Web Jobs Tools

Azure Stream Analytics Tools for Visual Studio 2.3.3000.2 Microsoft Azure Stream Analytics Tools for Visual Studio

C# Tools 2.8.3-beta6-62923-07. Commit Hash: 7aafab561e449da50712e16c9e81742b8e7a2969 C# components used in the IDE. Depending on your project type and settings, a different version of the compiler may be used.

Common Azure Tools 1.10 Provides common services for use by Azure Mobile Services and Microsoft Azure Tools.

Fabric.DiagnosticEvents 1.0 Fabric Diagnostic Events

JavaScript Language Service 2.0 JavaScript Language Service

JavaScript Project System 2.0 JavaScript Project System

JavaScript UWP Project System 2.0 JavaScript UWP Project System

JetBrains ReSharper Ultimate 2018.1.3 Build 112.0.20180626.160528 JetBrains ReSharper Ultimate package for Microsoft Visual Studio. For more information about ReSharper Ultimate, visit http://www.jetbrains.com/resharper. Copyright © 2018 JetBrains, Inc.

Markdown Editor 1.12.236 A full featured Markdown editor with live preview and syntax highlighting. Supports GitHub flavored Markdown.

Merq 1.1.19-rc (a4ffc1b) Command Bus, Event Stream and Async Manager for Visual Studio extensions.

Microsoft Azure HDInsight Azure Node 2.3.3000.2 HDInsight Node under Azure Node

Microsoft Azure Hive Query Language Service 2.3.3000.2 Language service for Hive query

Microsoft Azure Service Fabric Tools for Visual Studio 2.2 Microsoft Azure Service Fabric Tools for Visual Studio

Microsoft Azure Stream Analytics Language Service 2.3.3000.2 Language service for Azure Stream Analytics

Microsoft Azure Stream Analytics Node 1.0 Azure Stream Analytics Node under Azure Node

Microsoft Azure Tools 2.9 Microsoft Azure Tools for Microsoft Visual Studio 2017 - v2.9.10420.2

Microsoft Continuous Delivery Tools for Visual Studio 0.3 Simplifying the configuration of continuous build integration and continuous build delivery from within the Visual Studio IDE.

Microsoft JVM Debugger 1.0 Provides support for connecting the Visual Studio debugger to JDWP compatible Java Virtual Machines

Microsoft MI-Based Debugger 1.0 Provides support for connecting Visual Studio to MI compatible debuggers

Microsoft Visual Studio Tools for Containers 1.1 Develop, run, validate your ASP.NET Core applications in the target environment. F5 your application directly into a container with debugging, or CTRL + F5 to edit & refresh your app without having to rebuild the container.

Microsoft Visual Studio VC Package 1.0 Microsoft Visual Studio VC Package

Mono Debugging for Visual Studio 4.10.5-pre (ab58725) Support for debugging Mono processes with Visual Studio.

NuGet Package Manager 4.6.0 NuGet Package Manager in Visual Studio. For more information about NuGet, visit http://docs.nuget.org/.

Open Command Line 2.1.216 Opens a command line at the root of the project. Support for all consoles such as CMD, PowerShell, Bash etc. Provides syntax highlighting, Intellisense and execution of .cmd and .bat files.

ProjectServicesPackage Extension 1.0 ProjectServicesPackage Visual Studio Extension Detailed Info

ResourcePackage Extension 1.0 ResourcePackage Visual Studio Extension Detailed Info

SQL Server Data Tools 15.1.61804.210 Microsoft SQL Server Data Tools

ToolWindowHostedEditor 1.0 Hosting json editor into a tool window

TypeScript Tools 15.7.20419.2003 TypeScript Tools for Microsoft Visual Studio

Visual Basic Tools 2.8.3-beta6-62923-07. Commit Hash: 7aafab561e449da50712e16c9e81742b8e7a2969 Visual Basic components used in the IDE. Depending on your project type and settings, a different version of the compiler may be used.

Visual F# Tools 10.1 for F# 4.1 15.7.0.0. Commit Hash: 173513e369ffb7a1c4d5dccf83696d9aac2ab2d0. Microsoft Visual F# Tools 10.1 for F# 4.1

Visual Studio Code Debug Adapter Host Package 1.0 Interop layer for hosting Visual Studio Code debug adapters in Visual Studio

Visual Studio Spell Check Everywhere VSSpellCheckEverywhere An extension that enables spell checking within any Visual Studio file editor or tool window that uses WPF text boxes. https://GitHub.com/EWSoftware/VSSpellChecker

Visual Studio Spell Checker VSSpellChecker An editor extension that checks the spelling of comments, strings, and plain text as you type or interactively with tool windows. https://GitHub.com/EWSoftware/VSSpellChecker

Visual Studio Tools for Unity 3.7.0.1 Visual Studio Tools for Unity

Visual Studio Tools for Universal Windows Apps 15.0.27703.2035 The Visual Studio Tools for Universal Windows apps allow you to build a single universal app experience that can reach every device running Windows 10: phone, tablet, PC, and more. It includes the Microsoft Windows 10 Software Development Kit.

VisualLinter 1.1 Visual Studio JavaScript linter using ESLint.

VisualStudio.Mac 1.0 Mac Extension for Visual Studio

VsVim 2.5.0.0 VsVim is a Vim emulator for Visual Studio

Windows Machine Learning Generator Extension 1.0 Windows Machine Learning Visual Studio Extension Detailed Info

Xamarin 4.10.10.2 (35a01d8dc) Visual Studio extension to enable development for Xamarin.iOS and Xamarin.Android.

Xamarin Designer 4.12.1 (f3257e429) Visual Studio extension to enable Xamarin Designer tools in Visual Studio.

Xamarin.Android SDK 8.3.3.2 (HEAD/dffc59120) Xamarin.Android Reference Assemblies and MSBuild support.

Xamarin.iOS and Xamarin.Mac SDK 11.12.0.4 (64fece5) Xamarin.iOS and Xamarin.Mac Reference Assemblies and MSBuild support.

dustyghost avatar Sep 03 '18 12:09 dustyghost

I noticed you are mixing sync and async code...also maybe flip tracing on for server you maybe hitting a limit of some kind.

dcarr42 avatar Sep 03 '18 12:09 dcarr42

I noticed you are mixing sync and async code

We should be using Async, where are you seeing the mix?

dustyghost avatar Sep 03 '18 14:09 dustyghost

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

That will not play nice when under load.

dcarr42 avatar Sep 03 '18 16:09 dcarr42

Ooooooh! missed that! thanks will try it.

dustyghost avatar Sep 04 '18 07:09 dustyghost

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

dustyghost avatar Sep 04 '18 11:09 dustyghost