问题描述
如果我想使用 System.Net.HttpClient 提交一个 http get 请求,似乎没有添加参数的 api,这是正确的吗?
If I wish to submit a http get request using System.Net.HttpClient there seems to be no api to add parameters, is this correct?
是否有任何简单的 api 可用于构建不涉及构建名称值集合和 url 编码的查询字符串,然后最终连接它们?我希望使用类似 RestSharp 的 api(即 AddParameter(..))
Is there any simple api available to build the query string that doesn't involve building a name value collection and url encoding those and then finally concatenating them?I was hoping to use something like RestSharp's api (i.e AddParameter(..))
推荐答案
是的.
是否有任何简单的 api 可用于构建查询字符串不涉及构建名称值集合和 url 编码那些然后最后将它们连接起来?
当然:
var query = HttpUtility.ParseQueryString(string.Empty);
query["foo"] = "bar<>&-baz";
query["bar"] = "bazinga";
string queryString = query.ToString();
会给你预期的结果:
foo=bar%3c%3e%26-baz&bar=bazinga
您可能还会发现 UriBuilder
类很有用:
You might also find the UriBuilder
class useful:
var builder = new UriBuilder("http://example.com");
builder.Port = -1;
var query = HttpUtility.ParseQueryString(builder.Query);
query["foo"] = "bar<>&-baz";
query["bar"] = "bazinga";
builder.Query = query.ToString();
string url = builder.ToString();
会给你预期的结果:
http://example.com/?foo=bar%3c%3e%26-baz&bar=bazinga
您可以更安全地提供给您的 HttpClient.GetAsync
方法.
that you could more than safely feed to your HttpClient.GetAsync
method.
这篇关于为 System.Net.HttpClient 构建查询字符串获取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!