.NET HttpClient 将查询字符串和 JSON 正文添加到 POST
.NET HttpClient add query string and JSON body to POST
如何设置 .NET HttpClient.SendAsync() 请求以包含查询字符串参数和 JSON 主体(在 POST 的情况下)?
// Query string parameters
var queryString = new Dictionary<string, string>()
{
{ "foo", "bar" }
};
// Create json for body
var content = new JObject(json);
// Create HttpClient
var client = new HttpClient();
client.BaseAddress = new Uri("https://api.baseaddress.com/");
var request = new HttpRequestMessage(HttpMethod.Post, "something");
// Setup header(s)
request.Headers.Add("Accept", "application/json");
// Add body content
request.Content = new StringContent(
content.ToString(),
Encoding.UTF8,
"application/json"
);
// How do I add the queryString?
// Send the request
client.SendAsync(request);
我见过的每个例子都说要设置
request.Content = new FormUrlEncodedContent(queryString)
但后来我在 request.Content
中丢失了 JSON 主体初始化
我最终发现 Microsoft.AspNetCore.WebUtilities.QueryHelpers.AddQueryString()
这正是我所需要的。这允许我添加查询字符串参数,而无需手动构建字符串(并担心转义字符等)。
注意:我使用的是 ASP.NET 核心,但同样的方法也可以通过 Microsoft.Owin.Infrastructure.WebUtilities.AddQueryString()
新代码:
// Query string parameters
var queryString = new Dictionary<string, string>()
{
{ "foo", "bar" }
};
// Create json for body
var content = new JObject(json);
// Create HttpClient
var client = new HttpClient();
client.BaseAddress = new Uri("https://api.baseaddress.com/");
// This is the missing piece
var requestUri = QueryHelpers.AddQueryString("something", queryString);
var request = new HttpRequestMessage(HttpMethod.Post, requestUri);
// Setup header(s)
request.Headers.Add("Accept", "application/json");
// Add body content
request.Content = new StringContent(
content.ToString(),
Encoding.UTF8,
"application/json"
);
// Send the request
client.SendAsync(request);
我建议您为此目的使用 RestSharp。它基本上是 HttpWebRequest 的包装器,可以完全满足您的需求:使组合 url 和正文参数以及反序列化结果变得容易。
网站示例:
var client = new RestClient("http://example.com");
var request = new RestRequest("resource/{id}", Method.POST);
request.AddParameter("name", "value"); // adds to POST or URL querystring based on Method
request.AddUrlSegment("id", "123"); // replaces matching token in request.Resource
// easily add HTTP Headers
request.AddHeader("header", "value");
// add files to upload (works with compatible verbs)
request.AddFile(path);
// execute the request
IRestResponse response = client.Execute(request);
这很简单,对我有用:
responseMsg = await httpClient.PostAsJsonAsync(locationSearchUri, new { NameLike = "Johnson" });
请求正文看起来像 { NameLike:"Johnson" }
如何设置 .NET HttpClient.SendAsync() 请求以包含查询字符串参数和 JSON 主体(在 POST 的情况下)?
// Query string parameters
var queryString = new Dictionary<string, string>()
{
{ "foo", "bar" }
};
// Create json for body
var content = new JObject(json);
// Create HttpClient
var client = new HttpClient();
client.BaseAddress = new Uri("https://api.baseaddress.com/");
var request = new HttpRequestMessage(HttpMethod.Post, "something");
// Setup header(s)
request.Headers.Add("Accept", "application/json");
// Add body content
request.Content = new StringContent(
content.ToString(),
Encoding.UTF8,
"application/json"
);
// How do I add the queryString?
// Send the request
client.SendAsync(request);
我见过的每个例子都说要设置
request.Content = new FormUrlEncodedContent(queryString)
但后来我在 request.Content
我最终发现 Microsoft.AspNetCore.WebUtilities.QueryHelpers.AddQueryString()
这正是我所需要的。这允许我添加查询字符串参数,而无需手动构建字符串(并担心转义字符等)。
注意:我使用的是 ASP.NET 核心,但同样的方法也可以通过 Microsoft.Owin.Infrastructure.WebUtilities.AddQueryString()
新代码:
// Query string parameters
var queryString = new Dictionary<string, string>()
{
{ "foo", "bar" }
};
// Create json for body
var content = new JObject(json);
// Create HttpClient
var client = new HttpClient();
client.BaseAddress = new Uri("https://api.baseaddress.com/");
// This is the missing piece
var requestUri = QueryHelpers.AddQueryString("something", queryString);
var request = new HttpRequestMessage(HttpMethod.Post, requestUri);
// Setup header(s)
request.Headers.Add("Accept", "application/json");
// Add body content
request.Content = new StringContent(
content.ToString(),
Encoding.UTF8,
"application/json"
);
// Send the request
client.SendAsync(request);
我建议您为此目的使用 RestSharp。它基本上是 HttpWebRequest 的包装器,可以完全满足您的需求:使组合 url 和正文参数以及反序列化结果变得容易。
网站示例:
var client = new RestClient("http://example.com");
var request = new RestRequest("resource/{id}", Method.POST);
request.AddParameter("name", "value"); // adds to POST or URL querystring based on Method
request.AddUrlSegment("id", "123"); // replaces matching token in request.Resource
// easily add HTTP Headers
request.AddHeader("header", "value");
// add files to upload (works with compatible verbs)
request.AddFile(path);
// execute the request
IRestResponse response = client.Execute(request);
这很简单,对我有用:
responseMsg = await httpClient.PostAsJsonAsync(locationSearchUri, new { NameLike = "Johnson" });
请求正文看起来像 { NameLike:"Johnson" }