Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

asp.net

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.

like image 314
Tom Warner Avatar asked May 19 '17 18:05

Tom Warner


People also ask

How to set User-Agent in HttpClient?

Adding User-Agent header to single HttpRequest If you wish to add the User-Agent header to a single HttpRequestMessage , this can be done like this: var httpClient = new HttpClient(); var request = new HttpRequestMessage(HttpMethod.

What is User-Agent in Httpwebrequest?

You can used the User Agent to specify who you are, and the web server can return a Response with data appropriate for you client.

Whats is my User-Agent?

I bet you are now thinking, "what's my user agent?" It's an intermediary or middle man between you and the internet world. In simple words, it's a string of text that is unique for each software or browser on the internet and holds the technical information about your device and operating system.

Is User-Agent header required?

Some web servers respond to a missing User-Agent header by serving a legacy or HTML-only version of the website. This means that the visitor needs to provide a suitable User-Agent string to access the full, modern version of the website.


4 Answers

You can solve this easily using:

HttpClient _client = new HttpClient();
_client.DefaultRequestHeaders.Add("User-Agent", "C# App");
like image 60
Tom Warner Avatar answered Oct 07 '22 15:10

Tom Warner


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

var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (compatible; AcmeInc/1.0)");
like image 30
Martin Meixger Avatar answered Oct 07 '22 13:10

Martin Meixger


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
like image 33
Jan Bońkowski Avatar answered Oct 07 '22 15:10

Jan Bońkowski


Using JensG comment

Short addition: The UserAgent class also offers TryParse, which comes especially handy when there is no version number (for whatever reason). The RFC explicitly allows this case.

on this answer

using System.Net.Http;
using (var httpClient = new HttpClient())
{
    httpClient.DefaultRequestHeaders
      .UserAgent
      .TryParseAdd("Mike D's Agent");
    //User-Agent: Mike D's Agent
}
like image 41
spottedmahn Avatar answered Oct 07 '22 15:10

spottedmahn