我如何设置 .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 body的操作。
HttpRequestMessage
有一个RequestUri
属性;使用它来添加查询字符串(你可能需要创建一个新的Uri
对象并将RequestUri
设置为该对象)。 - Heretic MonkeyRequestUri
属性,加上我的端点 + 查询字符串信息,会覆盖我在HttpClient
对象上全局设置的HttpClient.BaseAddress
。但是这条路线引导我找到了我正在寻找的解决方案。 - Kevin R