Add a UserAgent to the IHttpClientFactory in .NET Core

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:

About briancaos

Developer at Pentia A/S since 2003. Have developed Web Applications using Sitecore Since Sitecore 4.1.
This entry was posted in .net, .NET Core, c# and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.