System.Net.HttpClient query string construction method for GET request
]question:
System.Net.HttpClient lacks an API to directly add GET request parameters. Is there an easier way to build a query string without manually creating a name-value collection, URL encoding, and connection?
Answer:
some. Easily build query strings without manual operation:
// 解析空查询字符串
var query = HttpUtility.ParseQueryString(string.Empty);
// 添加参数
query["foo"] = "bar&-baz";
query["bar"] = "bazinga";
// 将查询转换为字符串
string queryString = query.ToString();
This will generate the following query string:
foo=bar&-baz&bar=bazinga
]
Or, leveraging the UriBuilder class provides a more comprehensive solution:
// 为目标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();
This method generates the following URL:
http://example.com/?foo=bar&-baz&bar=bazinga
]
You can seamlessly integrate this URL into the GetAsync method of System.Net.HttpClient to perform GET requests with the required query parameters.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3