Skip to main content

Notifications

Announcements

No record found.

Customer experience | Sales, Customer Insights,...
Unanswered

Plugin Posting Api returning 400 Bad Request

Posted on by 2
Hi , I developing an plugin where when trigger by an button, but i meet an issue which is my httpclient acting weird, when i using postman to test its working correct return 201 created etc, even i work at consoleapp for testing purpose ,its also showing me 201 status created.
but when i implement to my plugin it show 400 bad request .  
 
here my code for reference . appreciate for help me 
 
 
 private async Task InsertInvoiceToBusinessCentralAsync(string jsonContent, string bcODataEndpoint)
 {
     using (HttpClient client = new HttpClient())
     {
         try
         {
             // Get a new access token
             string accessToken = await GetAccessToken(client);
             // Use the new access token for the Authorization header
             client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(/Bearer/, accessToken);
             // Set the content type to application/json
             client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(/application/json/));
             // Send a POST request to the Business Central OData endpoint for inserting the invoice
             HttpResponseMessage response = await client.PostAsync(bcODataEndpoint, new StringContent(jsonContent, System.Text.Encoding.UTF8, /application/json/));
            
             if (!response.IsSuccessStatusCode)
             {
                 if (response.StatusCode == HttpStatusCode.BadRequest)
                 {
                     // Handle Bad Request error
                     string responseContent = await response.Content.ReadAsStringAsync();
                     
                     // Log responseContent for debugging
                     // throw new CustomException(/Bad Request: / + responseContent);
                 }
                 else if (response.StatusCode == HttpStatusCode.Unauthorized)
                 {
                     // Handle Unauthorized error
                     // throw a CustomException(/Unauthorized/);
                 }
                 else
                 {
                     // Handle other HTTP status codes or exceptions
                     // throw new CustomException(/Other error: / + response.ReasonPhrase);
                 }
             }
         }
         catch (HttpRequestException ex)
         {
             // Handle network-related errors
             // throw new CustomException(/Network error: / + ex.Message);
         }
     }
 }
  private async Task<string> GetAccessToken(HttpClient client)
  {
      var values = new Dictionary<string, string>
  {
      { /grant_type/, /refresh_token/ },
      { /refresh_token/, refreshToken },
      { /client_id/, clientId },
      { /client_secret/, clientSecret }
  };
      var content = new FormUrlEncodedContent(values);
      var response = await client.PostAsync(tokenEndpoint, content);
      var responseString = await response.Content.ReadAsStringAsync();
      if (!response.IsSuccessStatusCode)
      {
          throw new Exception(/Failed to refresh access token./);
      }
      var tokenResponse = JsonConvert.DeserializeObject<Dictionary<string, string>>(responseString);
      return tokenResponse[/access_token/];
  }
 var jsonData = new
 {
     No = invoiceNumber.ToString().Trim(),
     Sell_to_Customer_No = accountNumber.ToString().Trim(),
     Company_Bank_Account_Code = bankAccountName.ToString().Trim(),
     Shortcut_Dimension_1_Code = branchLabel.ToString().Trim(),
     Shortcut_Dimension_2_Code = insurancelabel.ToString().Trim(),
     Salesperson_Code67594 = salespersoncode.ToString().Trim(),
     Posting_Description = PostingDe.ToString()
 };
 string jsonContent = JsonConvert.SerializeObject(jsonData);
 InsertInvoiceToBusinessCentralAsync(jsonContent,bcODataEndpoint).GetAwaiter().GetResult();
 SyncInvoiceDetails(invoice, service);

 

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

December Spotlight Star - Muhammad Affan

Congratulations to a top community star!

Top 10 leaders for November!

Congratulations to our November super stars!

Tips for Writing Effective Suggested Answers

Best practices for providing successful forum answers ✍️

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,280 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,214 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans