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, ...
Answered

Error while calling API 'The request was aborted: The connection was closed unexpectedly.'

(0) ShareShare
ReportReport
Posted on by 184

HI All,

I am facing an issue while calling sending a request to API.

Below is the error message.

Microsoft.Dynamics.Ax.Xpp.ErrorException: 'The request was aborted: The connection was closed unexpectedly.'

using Newtonsoft.Json.Linq;
using System.Net;
using System.IO;

public class WTL_6DeePaymentAPIservice
{
   public static void postPaymentAPI()
   {

       str                  _profileGUID =  "3ace35c3-6443-eb11-a812-000d3a20f116";
       str                 _transactionID = "12323553434";
       str                 _amount = "25.00";
       WTL_PaymentMode     _paymentMode = "1";
       str                _accountID = "1000107754";
       WTL_TransactionCurrencyID   _currencyCode = "QAR";
       WTL_AccountName     _customerName = "Harryson Jerico";
       str                 _amountPaid = "25";
       str                 _externalID = "4520941365";
       str                 _cardHolderName = "Patrisia Allen";
       str                 _modelValue = "113cvxrdu1";
       str                 _modelKey = "sample_key";
       str                 _paymentGWtoken = "vsE0aZWzPq02376";
       str                 _comment = "order payment";
       str                 _authToken = "xrzy6ryymust";
       str                 _orderType = "MakePayment";
       str                 _id = "";
       str                 _value = "";
        str                 _contactNumber = "(555) 555-1234";

        
        System.Exception                ex;
       

        try
        {
            JObject jObject = JObject::parse(WTL_6DeeAPITokenSerice::getToken());
            WebHeaderCollection httpHeaders = new WebHeaderCollection();
            httpHeaders.Add("Authorization", "Bearer "   strFmt("%1",jObject.SelectToken("$.access_token")));
            httpHeaders.Add("requestid", "7777777");
            httpHeaders.Add("sourcenode", "ERP");
            httpHeaders.Add("requesttimestamp", "2022-09-12");

            HttpWebRequest request = System.Net.WebRequest::Create("API URL");
    
            request.Headers = httpHeaders;
            request.Method = "POST";
            request.ContentType = "application/json";

            str json = WTL_6DJSONserializer::serializeJSON(
                                                            _profileGUID,
                                                            _transactionID,
                                                            strFmt("%1",_amount),
                                                            _paymentMode,
                                                            _accountID,
                                                            _currencyCode,
                                                            _customerName,
                                                            strFmt("%1",_amountPaid),
                                                            _externalID,
                                                            _cardHolderName,
                                                            _modelValue,
                                                            _modelKey,
                                                            _paymentGWtoken,
                                                            _comment,
                                                            _authToken,
                                                            _orderType,
                                                            _id,
                                                            _value,
                                                            _contactNumber);

            using (StreamWriter streamWriter = new StreamWriter(request.GetRequestStream()))
            {
                System.Byte[] postBytes;
                System.Text.Encoding encoding = System.Text.Encoding::get_ASCII();
                postBytes = encoding.GetBytes(json);
                streamWriter.Write(postBytes); // writing JSON

                using (System.Net.HttpWebResponse response = request.GetResponse())
                {
                    StreamReader streamRead = new StreamReader(response.GetResponseStream());
                    info(streamRead.ReadToEnd());
                }
            }

        }
        catch (ex)
        {
            throw error(ex.Message);
        }
        //catch (Exception::CLRError)
        //{
        //    throw error(AifUtil::getClrErrorMessage());
        //}
    }

}

I have pasted my whole code.

And while debugging I have found that the exception is thrown at " using (StreamWriter streamWriter = new StreamWriter(request.GetRequestStream())) "

Please help me to understand this issue and fix it

I have the same question (0)
  • D365_Wibes Profile Picture
    184 on at

    Sorry I am getting exception at line

    using (System.Net.HttpWebResponse response = request.GetResponse()

  • Martin Dráb Profile Picture
    237,880 Most Valuable Professional on at

    Please look at all details of the exception, not just the message. What is the type (e.g. WebException), is there any HTTP status code and so on?

    By the way, your code assumes that json variable contains ASCII string, but is it true? Please test whether your code writes what you expect to the request.

  • D365_Wibes Profile Picture
    184 on at

    Ascii_5F00_String.PNG

    API-Exception-details.PNG

    Thanks  for the reply Martin,

    I think it is writing the ASCII string, please let me if I am wrong

    Also I have seen the exception details and its of type : 

    Name Value Type
    ? $exception {"The remote server returned an error: (400) Bad Request."} Microsoft.Dynamics.Ax.Xpp.ErrorException

    Please help me to understand the root cause.

  • Martin Dráb Profile Picture
    237,880 Most Valuable Professional on at

    It seems that what you send to the web service isn't what the web service expects and is able to process.

    You'll need to review what you should send and what you're actually sending.

  • D365_Wibes Profile Picture
    184 on at

    You the mean the payload I am sending after encoding is having issues?

  • Martin Dráb Profile Picture
    237,880 Most Valuable Professional on at

    Yes, most likely. Although the problem could also be in headers.

  • D365_Wibes Profile Picture
    184 on at

    Thanks Martin, let me review and come back to you...

  • D365_Wibes Profile Picture
    184 on at

    Can you just tell me one more thins please?

    Is my way of encoding the payload is correct ?

  • Komi Siabi Profile Picture
    13,107 Most Valuable Professional on at

    Hi D365_Wibes,

    Just like Martin said your content might be the issue. I suggest, you copy the body of your message as it is in VS, and try the request on Postman. If it fails, compare that with the working sample payload. This will help you find the culprit.

    And this is me presuming me that you have done your testing with Postman from the onset before you started development.

  • D365_Wibes Profile Picture
    184 on at

    {
      "order_information": {
        "payment": {
          "ext_profile_id": "4dcea503-a366-eb11-a812-000d3abb5370",
          "transaction_id": "12323553434",
          "amount": "25.00",
          "payment_detail": [
            {
              "payment_mode": "1",
              "amount_paid": "25",
              "reference_external_id": "4520941365",
              "card_holder_name": "Patrisia Allen",
              "mode_detail": [
                {
                  "value": "113cvxrdu1",
                  "key": "sample_key"
                }
              ]
            }
          ],
          "account_id": "1000384111",
          "payment_gw_token": "vsE0aZWzPq02376",
          "comment": "order payment",
          "auth_token": "xrzy6ryymust",
          "currency_code": "QAR"
        },
        "customer_name": "Harryson Jerico",
        "order_type": "MakePayment",
        "dataset": {
          "param": [
            {
              "id": "",
              "value": ""
            }
          ]
        },
        "contact_number": "(555) 555-1234"
      }
    }

    This payload is getting passed via Postman

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
Martin Dráb Profile Picture

Martin Dráb 584 Most Valuable Professional

#2
André Arnaud de Calavon Profile Picture

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

#3
Sohaib Cheema Profile Picture

Sohaib Cheema 254 User Group Leader

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans