How do I set a default User Agent on an HttpClient?

It's easy to set a user agent on an HttpRequest, but often I want to use a single HttpClient and use the same user agent every time, rather than having to set it on each request.


Solution 1:

You can solve this easily using:

HttpClient _client = new HttpClient();
_client.DefaultRequestHeaders.Add("User-Agent", "C# App");

Solution 2:

Using DefaultRequestHeaders.Add(...) did not work for me.

var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (compatible; AcmeInc/1.0)");

Solution 3:

The following worked for me in a .NET Standard 2.0 library:

HttpClient client = new HttpClient();
ProductHeaderValue header = new ProductHeaderValue("MyAwesomeLibrary", Assembly.GetExecutingAssembly().GetName().Version.ToString());
ProductInfoHeaderValue userAgent = new ProductInfoHeaderValue(header);
client.DefaultRequestHeaders.UserAgent.Add(userAgent);
// User-Agent: MyAwesomeLibrary/1.0.0.0