Using a IHttpClientFactory to create HttpClient connections have a number of advantages, as you can configure several httpclients on startup. Each client will be reused, including the properties attached to that client.
In a previous post I showed how to create a Polly retry mechanism for a HttpClient. Adding a UserAgent to a HttpClient is even easier.
In the ConfigureServices() (in the Startup.cs file), add the following code:
services.AddHttpClient("HttpClient",
client =>
client.DefaultRequestHeaders.UserAgent.ParseAdd("my-bot/1.0")
);
This imaginary image service will get an image using the “HttpClient” connection. Every time a GET request is made, the UserAgent will be “my-bot/1.0“:
using System;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
namespace MyCode
{
public class ImageService
{
private readonly IHttpClientFactory _clientFactory;
public ImageService(IHttpClientFactory clientFactory)
{
_clientFactory = clientFactory;
}
public async Task<string> GetImage(string imageUrl)
{
try
{
var httpClient = _clientFactory.CreateClient("HttpClient");
using var response = await httpClient.GetAsync(imageUrl);
if (!response.IsSuccessStatusCode)
throw new Exception($"GET {imageUrl} returned {response.StatusCode}");
if (response.Content.Headers.ContentLength == null)
throw new Exception($"GET {imageUrl} returned zero bytes");
// ...
// Do something with the image being fetched
// ...
}
catch (Exception exception)
{
throw new Exception($"Failed to get image from {imageUrl}: {exception.Message}", exception);
}
}
}
}
MORE TO READ:
- Using C# HttpClient from Sync and Async code from briancaos
- HttpClient retry mechanism with .NET Core, Polly and IHttpClientFactory from briancaos
- C# HttpClient POST or PUT Json with content type application/json from briancaos
- Custom User Agent for HttpClient? from stackoverflow