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 :
Customer experience | Sales, Customer Insights,...
Answered

Sending a POST request using httpClient in a custom workflow activity in Dynamics CRM throws an exception "ThreadAbortException"

(1) ShareShare
ReportReport
Posted on by

I have a task to retrieve data created in an entity called "Denunciation" then do some structring and send this data (in JSON string format) to an API, so I need to make a POST request, everything works fine but when I want to send the post request, it throws this Excpetion

The Exception Details:

System.Threading.ThreadAbortException
  HResult=0x80131530
  Message=The thread has been abandoned.
  Source=System
  StackTrace:
   at System.Net.CookieModule.OnSendingHeaders(HttpWebRequest httpWebRequest)
   at System.Net.HttpWebRequest.UpdateHeaders()
   at System.Net.HttpWebRequest.SubmitRequest(ServicePoint servicePoint)
   at System.Net.HttpWebRequest.BeginGetRequestStream(AsyncCallback callback, Object state)
   at System.Net.Http.HttpClientHandler.StartGettingRequestStream(RequestState state)
   at System.Net.Http.HttpClientHandler.PrepareAndStartContentUpload(RequestState state)
--- End of stack trace from previous location ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at HclsDeclareProspect.DeclareProspect.d__28.MoveNext() in C:\Users\aimad.quouninich\Desktop\Projects\VDN\HclsDeclareProspect\DeclareProspect.cs:line 177

  This exception was originally thrown at this call stack:
    [External Code]
    HclsDeclareProspect.DeclareProspect.Execute(System.Activities.CodeActivityContext) in DeclareProspect.cs

My Code in the Execute Method:

      // Send POST request APIM
        CanalItem endpoint = CanalProvider.Retrieve(service, endpointReference);
        _trace  = string.Format("Endpoint : {0} \r\n", endpoint.Name);
        _trace  = string.Format("Endpoint Url : {0} \r\n", endpoint.Url);
        _trace  = string.Format("Endpoint Login : {0} \r\n", endpoint.Login);
        _trace  = string.Format("Endpoint Login : {0} \r\n", endpoint.Password);

        string url = $"{endpoint.Url}/denunciation";

        var content = new StringContent(requestJSON.ToString(), Encoding.UTF8, "application/json");
        content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

        HttpClient client = new HttpClient();

        client.DefaultRequestHeaders.Add("Apim-Subscription-Key", endpoint.Password);

        try
        {
            var result = await client.PostAsync(url, content);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }



If I removed the try-catch block the custom workflow and pluginRegistrationTool will exit without any error message and the subsequent line codes will not execute.

I have tried many things like using httpWebRequest instead of httpClient but when I tried to write to stream it exist with this error:

System.Security.SecurityException
  HResult=0x8013150A
  Message=Type Authorization Request Failed 'System.Net.WebPermission, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.
  Source=mscorlib
  StackTrace:
   at System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet)
   at System.Security.CodeAccessPermission.Demand()
   at System.Net.HttpWebRequest.get_Proxy()
   at System.Net.WebRequest.GetRequestStreamAsync()
   at HclsDeclareProspect.DeclareProspect.d__29.MoveNext() in C:\Users\aimad.quouninich\Desktop\Projects\VDN\HclsDeclareProspect\DeclareProspect.cs:line 186

  This exception was originally thrown at this call stack:
    [External Code]
    HclsDeclareProspect.DeclareProspect.Execute(System.Activities.CodeActivityContext) in DeclareProspect.cs
 

Using this code for the HttpWebrequest in place of httpClient:

 string url = $"{endpoint.Url}/denunciation";

        var content = new StringContent(requestJSON.ToString(), Encoding.UTF8, "application/json");
        content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

        var request = (HttpWebRequest)WebRequest.Create(new Uri(url));
        request.ContentType = "application/json";
        request.Method = "POST";
        request.Timeout = 4000; //ms
        var itemToSend = JsonConvert.SerializeObject(requestJSON);
        using (var streamWriter = new StreamWriter(await request.GetRequestStreamAsync()))
        {
            streamWriter.Write(itemToSend);
            streamWriter.Flush();
            streamWriter.Dispose();
        }

        // Send the request to the server and wait for the response:  
        using (var response = await request.GetResponseAsync())
        {
            // Get a stream representation of the HTTP web response:  
            using (var stream = response.GetResponseStream())
            {
                var reader = new StreamReader(stream);
                var message = reader.ReadToEnd();
            }
        }

I don't know what to do, please any help will be appreciated.

I have the same question (0)
  • Suggested answer
    Bipin D365 Profile Picture
    28,983 Moderator on at

    Hello,

    Can you please try below code

    Var result=client.PostAsync(url, content). Result;

  • Aimad Profile Picture
    on at

    I have tried this solution before, but sadly, it didn't work either, when that line of code gets executed the program and plugin-registration-tool exit without any error message.

    Still thanks for the suggestion, I want to know did you ever have this use case when you need to send a REST API request to a server, if yes can I see a code snippet, because it seems like I am the only one getting this problem as I didn't find a similar problem on the internet.

    Could it be something related to the CRM configuration? Does this mean the CRM service responsible for the custom workflows is aborting the thread?

  • Verified answer
    Bipin D365 Profile Picture
    28,983 Moderator on at

    Hi,

    Do you have profiler enabled for your custom workflow activity if so please remove and try.

    Also, would you be able to try the same code from plugin to see if it works.

  • Aimad Profile Picture
    on at

    "Do you have profiler enabled for your custom workflow activity if so please remove and try."

    I have removed the profiler then I used the Trace log, and I found this exception:

    Exception type: System.ServiceModel.FaultException`1[Microsoft.Xrm.Sdk.OrganizationServiceFault]
    Message: Could not load file or assembly 'Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)Detail:
    
    04225227-5173-447a-b128-d886c87b1f3e
    -2147220956
    
    http://go.microsoft.com/fwlink/?LinkID=398563&error=Microsoft.Crm.CrmException:80040224&client=platform
    Could not load file or assembly 'Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
    2022-05-18T08:37:41.8992124Z
    false
    PluginExecution
    
    PluginExecution
    
    

    UPDATE: The problem has been solved, many thanks man if you did'nt tell me to disable profile i would'nt notice that the problem is caused by Newtonsoft.json for some reason it worked when i was debugging but internally it was the cause also I need to add "Result"  var result = client.PostAsync(url, content).Result; like you said

    but I have some questions:

    1- Why when using debugger when i Got to the postasync line the program exit but now it worked when I see the Trace log ?!!

    2 - Why I need to use Result ?

    for the NewtonSoft.json I will use the standard library provided by the CRM

    Thanks man 

  • Verified answer
    Bipin D365 Profile Picture
    28,983 Moderator on at

    Hi,

    To solve Newtonsoft.json issue follow below blog

    www.inogic.com/.../

    You need to use Result to make your call sync.

    Debugger/profiler blocks some of external api call during testing.

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 > Customer experience | Sales, Customer Insights, CRM

#1
Tom_Gioielli Profile Picture

Tom_Gioielli 146 Super User 2025 Season 2

#2
#ManoVerse Profile Picture

#ManoVerse 59

#3
Gerardo Rentería García Profile Picture

Gerardo Rentería Ga... 52 Most Valuable Professional

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans