gpt4 book ai didi

c# - .NET HttpClient 向 POST 添加查询字符串和 JSON 正文

转载 作者:太空狗 更新时间:2023-10-29 18:24:27 26 4
gpt4 key购买 nike

如何设置 .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 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);

关于c# - .NET HttpClient 向 POST 添加查询字符串和 JSON 正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40290963/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com