dotnet / dotnet/dotnet-api-docs

Mention HttpClient's special behaviour when used by Blazor

Open
#8,021 1 comment 1 reaction 0 assignees View on GitHub
area-System.Net Pri3 untriaged
Dominant language
C#
Stars
949
Forks
1.7k
Avg merge
3d 27m
Merged PRs (30d)
49

Description

We should use a single instance of `HttpClient` to avoid the "socket exhaustion" [problem](https://docs.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests). From the [docs page](https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=net-6.0):

> HttpClient is intended to be instantiated once and re-used throughout the life of an application. Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads. This will result in SocketException errors.

But Blazor doesn't have this problem. The [Blazor docs](https://docs.microsoft.com/en-us/aspnet/core/blazor/call-web-api?view=aspnetcore-6.0&pivots=webassembly#httpclient-and-json-helpers) mention that it uses the browser's Fetch API (instead of TCP). The `dotnet new blazorwasm` template even uses a factory to create multiple instances of `HttpClient`:
````cs
builder.Services.AddScoped(sp =>
new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
````

(I also have a related StackOverflow [question and answer here](https://stackoverflow.com/q/72052956/9971404).)

The framework docs page (linked above) for HttpClient do not mention this. To be clear, and give users peace of mind, this special behaviour should be documented (briefly) on that page. Especially now that Blazor is a major part of the platform, and the `HttpClient` is a major part of Blazor.

I'm especially interested in how this is possible - is it that the implementation used by the Blazor SDK differs to that used by the server SDK?

Thanks!

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.