Invalid Request Body when i try to post to a Business Central API.

lawrence chikoore 0 Reputation points
2023-10-30T07:49:22.12+00:00
 static string ConvertCSVRecordToJson(CSVRecord record)
 {
     var jsonPayload = new
     {
         displayName = record.DisplayName,
         addressLine1 = record.Address1,
         city = record.City,
         country = record.Country,
         postalCode = record.PostalCode,
         email = record.Email,
         creditLimit = record.CreditLimit,
         taxLiable = record.TaxLiable,
         currencyCode = record.Currency
     };

     return JsonConvert.SerializeObject(jsonPayload);
 }


 static async Task SendDataToApiAsync(CSVRecord record)
 {
     using (HttpClientHandler handler = new HttpClientHandler())
     {
         handler.UseDefaultCredentials = true;

         using (HttpClient client = new HttpClient(handler))
         {
             // Convert the CSVRecord to JSON using ConvertCSVRecordToJson
             string jsonContent = ConvertCSVRecordToJson(record);

             // Create the HTTP content
             HttpContent httpContent = new StringContent(jsonContent, Encoding.UTF8, "application/json");

             try
             {
                 // Send the POST request to the API
                 HttpResponseMessage response = await client.PostAsync(apiEndpoint, httpContent);

                 if (response.IsSuccessStatusCode)
                 {
                     Console.WriteLine($"Data sent successfully to the API for record: {record.DisplayName}");
                 }
                 else
                 {
                     Console.WriteLine($"Failed to send data to the API for record: {record.DisplayName}");
                     // You can log additional error details here if needed
                 }
             }
             catch (HttpRequestException ex)
             {
                 Console.WriteLine($"HTTP request error: {ex.Message}");
                 // Handle the HTTP request error (e.g., network issues)
             }
             catch (Exception ex)
             {
                 Console.WriteLine($"An error occurred: {ex.Message}");
                 // Handle other exceptions
             }
         }
     }
 }
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,648 questions
{count} votes