Skip to content

System.Net.Http.HttpClient always fails on first attempted connection #95487

@mkellen1

Description

@mkellen1

Description

On the first attempt to connect to a web site, the connection always fails with a "Received an unexpected EOF or 0 bytes from the transport stream." exception. On the second and subsequent attempts it works as expected.

This was first apparent to me because the behavior appeared suddenly in PowerShell 7.2.x+. A simple Invoke-WebRequest fails the first time, then works fine for the rest of the session. Meanwhile, PowerShell 5 works as expected on the same platform.

Discussion over in the PowerShell repo in topic 20813 led to trying a purely C# code test (below) that suggests this is not a PowerShell issue, but some weird edge case that is surfaced in .NET

I can reproduce the behavior on multiple systems in my organization, on the LAN or not, even completely disconnected from the network using a loopback web server. I can also reproduce it under Windows Subsystem for Linux (kali) using Mono (6.8.0.105).

Reproduction Steps

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net;


namespace HTTP_Test
{
    class program
    {
        static void Main()
        {
            Task t = new Task(HTTP_GET);
            t.Start();
            Console.ReadLine();
        }

        static async void HTTP_GET()
        {
            var TARGETURL = "https://www.google.com/";

            HttpClientHandler handler = new HttpClientHandler();

            Console.WriteLine("GET: + " + TARGETURL);

            // ... Use HttpClient.
            HttpClient client = new HttpClient(handler);

            HttpResponseMessage response = await client.GetAsync(TARGETURL);
            HttpContent content = response.Content;

            // ... Check Status Code
            Console.WriteLine("Response StatusCode: " + (int)response.StatusCode);

        }
    }
}

Expected behavior

Network connection should work the first time.

Actual behavior

Connection fails on first attempt every time.

Regression?

No response

Known Workarounds

Use PowerShell 5.

Configuration

My system is .NET release 533325, Windows 10 22H2 (19045.3570) on an x64.

Has been reproduced on multiple versions of Windows 10 on various hardware platforms, including a VDI. This has also been reproduced under Windows Subsystem for Linux on my laptop.

Other information

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions