HTTP, REST and Networking
Never create a new HttpClient per request in long-running apps (socket exhaustion). Use IHttpClientFactory or a shared static instance with PooledConnectionLifetime.
Auth: Bearer tokens, OAuth2/OIDC (MSAL for Microsoft Entra ID), API keys in headers. Handle 429 (retry-after) and pagination.
Other networking: TcpClient/TcpListener, UdpClient, Socket (async), SslStream, ClientWebSocket, named pipes, gRPC clients (Grpc.Net.Client; codegen is C#, so wrap it in a C# project), SignalR client, email (MailKit), FTP/SFTP (FluentFTP, SSH.NET).
Imports System.Net.Http
Imports System.Net.Http.Json
Public Class WeatherClient
Private ReadOnly _http As HttpClient
Public Sub New(http As HttpClient) ' injected via IHttpClientFactory
_http = http
End Sub
Public Async Function GetForecastAsync(city As String, ct As Threading.CancellationToken) As Task(Of Forecast)
Using resp = Await _http.GetAsync($"forecast?city={Uri.EscapeDataString(city)}", ct)
If resp.StatusCode = Net.HttpStatusCode.NotFound Then Return Nothing
resp.EnsureSuccessStatusCode()
Return Await resp.Content.ReadFromJsonAsync(Of Forecast)(cancellationToken:=ct)
End Using
End Function
End Class
' Registration
builder.Services.AddHttpClient(Of WeatherClient)(Sub(c)
c.BaseAddress = New Uri("https://api.example.com/")
c.Timeout = TimeSpan.FromSeconds(10)
End Sub).AddStandardResilienceHandler() ' Microsoft.Extensions.Http.Resilience