我可以使用一些帮助来将参数传递给 HttpClient.PostAsync() 调用。
我的第一个示例来自我已成功运行的代码...
HttpClient client = new HttpClient();
// The URL of the API endpoint
string url = "https://user.auth.xboxlive.com/user/authenticate";
// The parameters to send in the POST request
var values = new Dictionary<string, string>
{
{ "param1", "value1" },
{ "param2", "value2" },
{ "param3", "value3" },
};
// Encode the parameters as form data
FormUrlEncodedContent content = new FormUrlEncodedContent(values);
// Send the POST request
HttpResponseMessage response = await client.PostAsync(url, content);
但是对于其他调用,我需要发送嵌套参数。
从概念上讲,它看起来像下面的代码。
我意识到这是错误的,因为它甚至不是合法的 C# 语法。
那么有人可以告诉我我应该做什么来实现这一目标吗?
尽管我作为一名开发人员已经有很多年了,但当涉及到 Http 的东西时,我还处于小学水平。
HttpClient client = new HttpClient();
// The URL of the API endpoint
string url = "https://user.auth.xboxlive.com/user/authenticate";
// The parameters to send in the POST request
var values = new Dictionary<string, string>
{
{ "param1", "value1" },
{ "param2",
{
{"param2a", "values2a"},
{"param2b", "values2b"},
{"param2c", "values2c"}
},
{ "param3", "value3" },
};
// Encode the parameters as form data
FormUrlEncodedContent content = new FormUrlEncodedContent(values);
// Send the POST request
HttpResponseMessage response = await client.PostAsync(url, content);
感谢您提供的任何帮助
HTML 表单不支持嵌套结构,否则 JSON 是通用标准。这样您就可以使用嵌套的
Dictionary
并更改您的响应类型
var values = new Dictionary<string, object>
{
{ "param1", "value1" },
{ "param2", new Dictionary<string, string>
{
{"param2a", "values2a"},
{"param2b", "values2b"},
{"param2c", "values2c"}
}
},
{ "param3", "value3" },
};
string jsonContent = System.Text.Json.JsonSerializer.Serialize(values);
StringContent content = new StringContent(jsonContent, System.Text.Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(url, content);