Accessing third party REST API from SageCRM.Net using PostASync()

SOLVED

Bit of long shot this one, I am trying to access a REST API from Sage CRM using the SageCRM.Net extensions. I'm using HttpClient and PostAsync() to call the REST API. It looks something like this : 

private async Task<(bool success, string errorMessage)> Upload()
{

//set up login details
var login = new Login
{
//email address
Key = "[email protected]",
//password
Secret = "password"
};
var json = JsonConvert.SerializeObject(login);
var data = new StringContent(json, Encoding.UTF8, "application/json");

//login to system
try
{
var client = new HttpClient();
var response = await client.PostAsync("">myrestservice.co.uk/.../login", data);
}
catch (ThreadAbortException ex)
{
return (false, ex.Message);
}
catch (Exception ex)
{
return (false, ex.Message);
}


Its failing on the await client.PostAsync("">myrestservice.co.uk/.../login", data); line with a "Thread was being aborted." exception. My code runs fine if I put it in a console application but as soon as I put it in the SageCRM.Net dll I am building I am always getting this "Thread was being aborted" exception when I attempt to call PostAsync().

Its the first time I have tried using PostAsync() in a Sage CRM dll and I was wondering if anyone else has had any success with this or if there is something I need to do in my DLL to stop the "Thread was being aborted" exception ?

  • 0

    I've not tried this myself - but : when you call a CRM .Net function then it creates a new AppDomain, does the work necessary to build the page and then unloads the AppDomain. So it's not like it's a running process. What I guess is happening here is the AppDomain is unloading and terminating your thread. Of course, in a console app you have a running process, so it'll wait for the async method to return.

  • +1
    verified answer

    I'm assuming you are not waiting for the task to complete.

    Top level CRM methods (e.g. BuildContents) do not support await, so when calling any async methods you will need to block the main thread, otherwise the main thread will exit before the task can complete.

    You can block the main thread until the task completes by calling any async methods like:

    var result = Upload().GetAwaiter().GetResult();

  • 0

    Thanks Chris And John for your suggestions! I have managed to call the REST API using the .GetAwaiter().GetResult(); methods and its now not aborting the threads. Now I just need to update the rest of my library with .GetAwaiter().GetResult() and I should be good to go.

    Thanks again!