Search code examples
c#.netformatexception

How do I solve "Exception thrown: 'System.FormatException' in System.Net.Http.dll"?


This is the method that executes whenever a WPF button is clicked:

private void Dial(object sender, RoutedEventArgs e)
{
    SendDataAsync(sender, e);
}

private async Task SendDataAsync(object sender, RoutedEventArgs e)
{   
    //this method does the actual dialing part
    var toSend = new Dictionary<string, string>
    {
        { "ClientID", ConfigurationManager.AppSettings["ClientID"] },
        { "PhoneNumber", numberToSend }
    };

    string jsonString = JsonSerializer.Serialize(toSend);

    var content = new StringContent(jsonString);

    content.Headers.Add("Content-type", "text/json");
    content.Headers.Add("Content-type", "application/json");

    var response = await client.PostAsync("https://webhook.site/4788266d-9caf-4747-a3d2-09777b233435", content);

    var responseString = await response.Content.ReadAsStringAsync();

}

I've tried commenting out either of the "content.headers.add" lines, but the error remained.

This is the full exception as shown in the output from debug:

Exception thrown: 'System.FormatException' in System.Net.Http.dll


Solution

  • From Panagiotis Kanavos' comment at Mar 23 at 9:55:

    You can't have two content types. You can replace all this code with PostAsJsonAsync eg await client.PostAsJsonAsync(url,toSend);