Kev*_*n R 9 c# dotnet-httpclient
如何设置.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);
Run Code Online (Sandbox Code Playgroud)
我见过的每个例子都说要设置
request.Content = new FormUrlEncodedContent(queryString)
Run Code Online (Sandbox Code Playgroud)
但后来我丢失了我的JSON主体初始化 request.Content
Kev*_*n R 13
我最终发现Microsoft.AspNetCore.WebUtilities.QueryHelpers.AddQueryString()这就是我所需要的.这允许我添加查询字符串参数,而无需手动构建字符串(并担心转义字符等).
注意:我正在使用ASP.NET Core,但也可以使用相同的方法 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);
Run Code Online (Sandbox Code Playgroud)