Query string construction method for System.Net.HttpClient GET request
Question:
System.Net.HttpClient lacks API to directly add GET request parameters. Is there an easier way to build query strings without manually creating name-value collections, URL encoding, and concatenation?
Answer:
Yes. Easily build query strings with no manual effort:
<code class="language-csharp">// 解析空查询字符串 var query = HttpUtility.ParseQueryString(string.Empty); // 添加参数 query["foo"] = "bar&-baz"; query["bar"] = "bazinga"; // 将查询转换为字符串 string queryString = query.ToString();</code>
This will generate the following query string:
<code>foo=bar%3c%3e%26-baz&bar=bazinga</code>
Alternatively, utilizing the UriBuilder class provides a more comprehensive solution:
<code class="language-csharp">// 为目标URL创建一个UriBuilder var builder = new UriBuilder("http://example.com"); builder.Port = -1; // 解析查询字符串 var query = HttpUtility.ParseQueryString(builder.Query); // 添加参数 query["foo"] = "bar&-baz"; query["bar"] = "bazinga"; // 更新UriBuilder的查询字符串 builder.Query = query.ToString(); // 获取完整的URL string url = builder.ToString();</code>
This method generates the following URL:
<code>http://example.com/?foo=bar%3c%3e%26-baz&bar=bazinga</code>
You can seamlessly integrate this URL into the GetAsync method of System.Net.HttpClient to perform a GET request with the required query parameters.
The above is the detailed content of How Can I Easily Build Query Strings for System.Net.HttpClient GET Requests?. For more information, please follow other related articles on the PHP Chinese website!