Send HTTP Request in C#


It’s been a while since I send HTTP Request in C#.
So, I wrote this post as my note.

Prerequisites

  • .NET Core 3.1
  • C# v8
  • Visual Studio 2019
  • Windows 10 v21H1

Not good case

If it’s a trial code that only you use, this is fine. Not suitable for commercial services.

public class SomeoneApiClient
{
	public async Task<Result> GetToken(string accountId, string apiKey)
	{
	    var url = $"https://example.com/api/{accountId}/token";
	    var request = new HttpRequestMessage(HttpMethod.Get, url);
	    request.Headers.Add(@"Authorization", $"Bearer {accountId}:{apiKey}");
	
	    // HttpClient in System.Net.Http namespace.
	    HttpClient client = new HttpClient();
	    var response = await client.SendAsync(request);
	    var jsonRaw = await response.Content.ReadAsStringAsync();
	
	    // JsonConvert is Newtonsoft.Json namespace.
	    Result json = JsonConvert.DeserializeObject<Result>(jsonRaw);
	    return json;
	}
}

public class Result
{
    public string AccessToken { get; set; }
}

If you are possible, HTTPClient instances should be shared within the your application. Because it will be exhausted by the death of the sockets.

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. Below is an example using HttpClient correctly.

https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netframework-4.8#remarks