Search code examples
c#httphttpclient

C# - Passing nested parameters to HttpClient PostAsync


I could use some help with passing parameters to HttpClient.PostAsync() calls Please.

My first example is from code that I have running successfully...

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

But for other calls there are nested parameters that I need to send. Conceptually, it would look something like this code below. I realize this is wrong because it's not even legal C# syntax.
So could someone show me what I'm supposed to do to achieve that? Despite my years as a developer, I'm at gradeschool level when it comes to Http stuff.

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

Thanks for any help you can give


Solution

  • HTML forms don't support nested structures and JSON is the common standard otherwise. With this you can use nested Dictionarys and change your response type

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