代码之家  ›  专栏  ›  技术社区  ›  user2191367

C#-将嵌套参数传递给HttpClient PostAsync

  •  0
  • user2191367  · 技术社区  · 2 年前

    我可以使用一些帮助将参数传递到HttpClient。PostAsync()调用Please。

    我的第一个例子是我成功运行的代码。。。

                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);
    

    谢谢你的帮助

    1 回复  |  直到 2 年前
        1
  •  1
  •   emptyjar    2 年前

    HTML表单不支持嵌套结构,否则JSON是常见的标准。有了它,您可以使用嵌套 Dictionary s并更改您的响应类型

    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);