Calling external web services from CRM Online Sandboxed plugin

I have seen this question many times ā€“ Can you call external endpoints from within a plugin running inside Sandbox of Dynamics CRM Online?

Recently I was riddled with the same situation where the sandbox did not allow me to call an external endpoint.

On the positive note, I was able to overcome this issue with a little tweak and I thought it might be useful to share with the community.

 

Problem

Say we need to call a JSON based web service from within a CRM plugin

 

Code that would not work

var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( "Bearer", wsKey);
client.BaseAddress = new Uri("<your ws url>");
                
//Say jsonBody is typed object
HttpResponseMessage response = await client.PostJsonAsync("", jsonBody);

if (response.IsSuccessStatusCode)
{
        string result = await response.Content.ReadAsStringAsync();
        var typedResult= JsonConvert.DeserializeObject<Results>(result);      
}

 

Modified Code that will work

var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( "Bearer", wsKey);
client.BaseAddress = new Uri("<your ws url>");
                
//Rather than using a typed object, construct the JSON object manually using strings
string jsonBody =  "{\"Inputs\": {\"input1\": {\"ColumnNames\": [\"AnnualReview\",\"Category\"],........";

//Rather than using PostJsonAsync use PostAsync
 HttpResponseMessage response = await client
                   .PostAsync("", new StringContent(jsonBody , Encoding.UTF8, "application/json"))
                    .ConfigureAwait(false);

if (response.IsSuccessStatusCode)
{
        string result = await response.Content.ReadAsStringAsync();
		//Rather than using DeserializeObject, parse the json string manually
        var parsingResp = ((string)result).ParseWSResponse();
}

 

Learning

In nutshell, my experience has been that you can call external services as long as you stick to base .NET classes that come packaged with the framework out of the box.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s