web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
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,346
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:
I have the same question (0)
  • Suggested answer
    Mohamed Amine Mahmoudi Profile Picture
    26,445 Super User 2025 Season 2 on at
     
    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
  • Martin Dráb Profile Picture
    237,976 Most Valuable Professional on at
    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.
  • haroonattari Profile Picture
    2,346 on at
    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.
  • Mohamed Amine Mahmoudi Profile Picture
    26,445 Super User 2025 Season 2 on at
     
    Is your issue fixed ? If yes, then please verify the answers that helped.
     
    Best regards,
    Mohamed Amine MAHMOUDI
  • Martin Dráb Profile Picture
    237,976 Most Valuable Professional on at
    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.
  • haroonattari Profile Picture
    2,346 on at
     
    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
    237,976 Most Valuable Professional on at
    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.
  • Navneeth Nagrajan Profile Picture
    2,438 Super User 2025 Season 2 on at
    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!)!;
     
     
  • haroonattari Profile Picture
    2,346 on at
     
    Here is the screen shot which shows exception details for your reference. 
     
  • Suggested answer
    Martin Dráb Profile Picture
    237,976 Most Valuable Professional on at
    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.

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

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > Finance | Project Operations, Human Resources, AX, GP, SL

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 449 Super User 2025 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 422 Most Valuable Professional

#3
BillurSamdancioglu Profile Picture

BillurSamdancioglu 239 Most Valuable Professional

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans