97

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.

Selim Yildiz
  • 5,254
  • 6
  • 18
  • 28
Tom Warner
  • 3,193
  • 3
  • 17
  • 24

5 Answers5

149

You can solve this easily using:

HttpClient _client = new HttpClient();
_client.DefaultRequestHeaders.Add("User-Agent", "C# App");
lmiguelvargasf
  • 63,191
  • 45
  • 217
  • 228
Tom Warner
  • 3,193
  • 3
  • 17
  • 24
94

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

var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (compatible; AcmeInc/1.0)");
Martin Meixger
  • 2,547
  • 24
  • 26
  • 1
    This _should_ be the accepted answer. – Owen Feb 03 '22 at 21:51
  • I did this with word-word-name.name@domain.com and it failed , it expects a more standard format UA so I changed it to Mozilla/5.0 (compatible; word-word-name.name@domain.com) – Jeff May 06 '22 at 20:24
19

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
Jan Bońkowski
  • 538
  • 9
  • 22
  • 4
    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. – JensG May 04 '19 at 10:31
17

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
}
spottedmahn
  • 14,823
  • 13
  • 108
  • 178
-1
string agent="ClientDemo/1.0.0.1 test user agent DefaultRequestHeaders";
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("User-Agent", agent);

remark: use this structure to generate the agent name User-Agent: product / product-version comment

  • product: Product identifier
  • product-version: Product version number.
  • comment: None or more of the infomation Comments containing product, for example.

references