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.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You can solve this easily using:
HttpClient _client = new HttpClient();
_client.DefaultRequestHeaders.Add("User-Agent", "C# App");
Method 2
Using DefaultRequestHeaders.Add(...) did not work for me.
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (compatible; AcmeInc/1.0)");
Method 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
Method 4
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
}
Method 5
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.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0