Skip to main content

Notifications

Finance | Project Operations, Human Resources, ...
Suggested answer

500 Internal Server Error During PUT Request from D365FO to Third-Party App

(3) ShareShare
ReportReport
Posted on by 2,323
Hi everyone,
 
I am working on an integration that updates main account data from D365FO to a third-party application. The integration works well if the account exists in the third-party application. However, if the record is deleted directly from the third-party application, an error occurs when the application tries to update it.
 
Error: 
System.Net.WebException: The remote server returned an error: (500) Internal Server Error.
 
Expected Behavior: 
When updating the same record from Postman, a more specific and user-friendly error message is displayed:
> Database operation expected to affect 1 row(s) but actually affected 0 row(s). 
> Data may have been modified or deleted since entities were loaded.
 
I would appreciate any help from experts to identify the cause of this issue. Here is the sample code I used if needed.
 
internal final class APIClientCallRunnableClass
{
    public static void main(Args _args)
    {
        APIClientCallRunnableClass::APICallHttpWebRequest();
    }
    public static void APICallHttpWebRequest()
    {
        System.Net.HttpWebRequest    request;
        System.IO.Stream             stream;
        System.Exception             sysEx;
        System.Net.WebException     webEx;

        str apiUrl, apimSubscriptionKey, xClientId, mimeType, responseBody;

        apiUrl              = 'https://3rd-party-application-api-url';
        apimSubscriptionKey = 'my-subscription-key';
        xClientId           = 'my-client-id';
        mimeType            = 'application/json';

        request = System.Net.WebRequest::Create(apiUrl) as System.Net.HttpWebRequest;
        request.Method = 'PUT';
        request.ContentType = 'application/json';

        // Set the request headers
        System.Net.WebHeaderCollection headerCollection = request.Headers;
        headerCollection.Set('Ocp-Apim-Subscription-Key', apimSubscriptionKey);
        headerCollection.Set('X-Client-Id', xClientId);
        headerCollection.Set('name', mimeType);

        var utf8 = System.Text.Encoding::get_UTF8();

        // Set the request body
        var byteArrayPayload = utf8.GetBytes("{\"accountCode\":\"999991\",\"accountName\":\"999991 ADDED/UPDATED AGAIN\",\"entityCode\":\"USMF\",\"entityName\":\"Contoso Entertainment System USA\",\"id\":9739}");
        
        try
        {
            // send out the payload
            using(System.IO.Stream dataStream = request.GetRequestStream())
            {
                dataStream.Write(byteArrayPayload, 0, byteArrayPayload.Length);
            }

            // request.GetResponse() may already result in an error if the request was e.g. a Bad Request(Status Code 400). This should be handled upstream via our global error handling.
            using(System.Net.HttpWebResponse response = request.GetResponse() as System.Net.HttpWebResponse)
            {
                stream = response.GetResponseStream();
                System.IO.StreamReader reader = new System.IO.StreamReader(stream);
                responseBody = reader.ReadToEnd();
            }
        }
        catch (webEx)
        {
            Error(strFmt('An error occured while updating record: %1', webEx.Message));
        }
        catch (sysEx)
        {
            Error(strFmt("An error occured while updating record: %1", sysEx.Message));
        }
    }
}
 
Categories:
  • Suggested answer
    Martin Dráb Profile Picture
    Martin Dráb 230,934 Most Valuable Professional on at
    500 Internal Server Error During PUT Request from D365FO to Third-Party App
    I think you'll find the text in the Response property. You'll need code like this:
    System.Net.WebResponse response = webEx.Response();
    Encoding encoding = System.Text.Encoding::UTF8;
    
    using (var reader = new System.IO.StreamReader(response.GetResponseStream(), encoding))
    {
        str responseText = reader.ReadToEnd();
    }

    Of course, it assumes that you actually catch the exception.

  • haroonattari Profile Picture
    haroonattari 2,323 on at
    500 Internal Server Error During PUT Request from D365FO to Third-Party App
     
    Here is the screen shot which shows exception details for your reference. 
     
  • Navneeth Nagrajan Profile Picture
    Navneeth Nagrajan 1,424 Super User 2025 Season 1 on at
    500 Internal Server Error During PUT Request from D365FO to Third-Party App
    Hi @HarooNattari,
     
    A few question/suggestions:
    1. Are you able to retrieve the URL in postman through the GET or POST method in postman? Better check through a GET parameter, as suggested Md Amine.
    request.Method = 'PUT';
    2. Also, when you pass the parameters through your URL are you getting a response or a 401 unauthorized or a 400 request error?
    3. Because your request content/type is a .json you can try deserializing the content.
      var data = JsonSerializer.Deserialize<JsonNode>(response.Content!)!;
     
     
  • Martin Dráb Profile Picture
    Martin Dráb 230,934 Most Valuable Professional on at
    500 Internal Server Error During PUT Request from D365FO to Third-Party App
    Your second screenshot doesn't show properties of the exception. It's just a dialog informing your that an exception occurred, but you should expand the details to learn more about the exception. Use View details (and possibly Show Call Stack) button.
  • haroonattari Profile Picture
    haroonattari 2,323 on at
    500 Internal Server Error During PUT Request from D365FO to Third-Party App
     
    Here are the screen shots from the postman and debugger. 
     
     â€‹â€‹â€‹â€‹â€‹â€‹â€‹
    It's also strange that this exception is unhandled, while you're trying to handle it in your code.

     
  • Martin Dráb Profile Picture
    Martin Dráb 230,934 Most Valuable Professional on at
    500 Internal Server Error During PUT Request from D365FO to Third-Party App
    Please show us screenshots of the reponse in Postman and the object in debugger where you're seeing the value 500. Statements like "it is showing" aren't detailed enough.
  • Mohamed Amine Mahmoudi Profile Picture
    Mohamed Amine Mahmoudi 14,015 Super User 2025 Season 1 on at
    500 Internal Server Error During PUT Request from D365FO to Third-Party App
     
    Is your issue fixed ? If yes, then please verify the answers that helped.
     
    Best regards,
    Mohamed Amine MAHMOUDI
  • haroonattari Profile Picture
    haroonattari 2,323 on at
    500 Internal Server Error During PUT Request from D365FO to Third-Party App
    Thank you both for your reply. 
     
    @Mohamed Amine Mahmoudi The suggestion will definitely work but it will slow down the system's performance with those GET calls to check if records exist.
     
    @Martin Dráb yes, I am getting a detailed message on Postman but when I am looking at exception data while debugging in X++, it is only showing a 500 Internal Server error and nothing else. The code snippet I added is only catching System.Net.WebException and does not contain the details I am getting on Postman for the same operation.
  • Martin Dráb Profile Picture
    Martin Dráb 230,934 Most Valuable Professional on at
    500 Internal Server Error During PUT Request from D365FO to Third-Party App
    Are you saying that you get a response object with detailed messages when calling the web service from Postman and want to add code to apiCallHttpWebRequest() to expose this data?
     
    Your description also suggest that you get an unhandled exception, which sounds strange (because you're catching System.Exception). Please tell us more about the observed behaviour.
  • Suggested answer
    Mohamed Amine Mahmoudi Profile Picture
    Mohamed Amine Mahmoudi 14,015 Super User 2025 Season 1 on at
    500 Internal Server Error During PUT Request from D365FO to Third-Party App
     
    It's normal to get this error message since the record doesn't exist in the third-party application.
    I suggest you do a GET before the PUT if the record exists you must do PUT if not POST.
     
    Best regards,
    Mohamed Amine MHMOUDI

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

Announcing Our 2025 Season 1 Super Users!

A new season of Super Users has arrived, and we are so grateful for the daily…

Vahid Ghafarpour – Community Spotlight

We are excited to recognize Vahid Ghafarpour as our February 2025 Community…

Congratulations to the January Top 10 leaders!

Check out the January community rock stars...

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 292,111 Super User 2025 Season 1

#2
Martin Dráb Profile Picture

Martin Dráb 230,934 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Product updates

Dynamics 365 release plans