Posting Name Value Pairs with HttpClient

Kmcnet 691 Reputation points
2022-09-05T01:29:25.913+00:00

Hello everyone and thanks for the help in advance. I am writing an application that needs to POST Name-Value pairs along with some header details to an external api. Here is my code to this point:

            HttpClient client = new HttpClient();  
  
            NameValueCollection nameValueCollection = new NameValueCollection();  
            nameValueCollection.Add("media_url", "https://mysite.com/test_fax.pdf");  
            nameValueCollection.Add("connection_id", "12345678");  
            nameValueCollection.Add("to", "+19999999999");  
            nameValueCollection.Add("from", "+19999999999");  
            var webRequest = new HttpRequestMessage(HttpMethod.Post, "https://api.telnyx.com/v2/faxes")  
            {  
                Content = new StringContent(nameValueCollection.ToString(), Encoding.UTF8, "application/x-www-form-urlencoded")  
            };  
            webRequest.Headers.Add("Authorization", "Bearer KEY12345");  
  
            var response = client.Send(webRequest);  
            var reader = new StreamReader(response.Content.ReadAsStream());  
            var responseBody = reader.ReadToEnd();  

I am receiving an error message stating the api requires a parameter connection_id. Looks like I'm not transmitting data, but not sure why. Any help would be appreciated.

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,199 questions
{count} votes

Accepted answer
  1. Viorel 111.8K Reputation points
    2022-09-05T09:12:27.91+00:00

    Try something like this:

    string d = string.Join( "&",  
        nameValueCollection  
            .AllKeys  
            .SelectMany( k => nameValueCollection.GetValues( k ).Select( v => $"{Uri.EscapeDataString( k )}={Uri.EscapeDataString( v )}" ) ) );  
    Content = new StringContent(d, Encoding.UTF8, "application/x-www-form-urlencoded");  
    

    If it works, maybe there are more elegant solutions.

    2 people found this answer helpful.

0 additional answers

Sort by: Most helpful