简体   繁体   中英

C# HttpClient adding “User-Agent” header shows up as several different headers

When adding a "User-Agent" header to HttpClient it shows up as several User-Agent headers instead in the request. It seems as the string added as User-Agent breaks upon a space character by default and then they are added as separate User-Agents. How can I add a single User-Agent string with spaces using HttpClient ?

var cookieContainer = new CookieContainer();
var handler = new HttpClientHandler();
handler.CookieContainer = cookieContainer;
var httpClient = new HttpClient(handler);
httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36");
//Did not work either, same result
//httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36");
//httpClient.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36");

在此输入图像描述

在此输入图像描述

You should not worry about that. It splits your user agent into several parts internally, because that is how User-Agent header defined in RFC :

The User-Agent request-header field contains information about the
user agent originating the request. This is for statistical purposes, the tracing of protocol violations, and automated recognition of user agents for the sake of tailoring responses to avoid particular user
agent limitations. User agents SHOULD include this field with
requests. The field can contain multiple product tokens (section 3.8) and comments identifying the agent and any subproducts which form a
significant part of the user agent. By convention, the product tokens are listed in order of their significance for identifying the
application.

User-Agent = "User-Agent" ":" 1*( product | comment )

So what you see are those "product tokens" and if you explore each - you will see that they have Product and Comment properties.

However, this does not mean it will send this as 6 headers. It will send one User-Agent header, same as you provided as string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM