Using WebClient to call external service from CRM Online Sandboxed Plugin (HTTP POST and JSON)

Sharing a sample code that can be used to send JSON data using POST to an external service inside CRM Online Plugin. As plugin runs in sandbox mode we cannot reference Newtonsoft’s JSON.NET library The other option could be to use ILMerge, which isn’t that elegant.

Here, basically we are passing some information related to lead to an external service on Post Create of it.

<p>using Microsoft.Xrm.Sdk;<br />
using System;<br />
using System.IO;<br />
using System.Net;<br />
using System.Runtime.Serialization.Json;<br />
using System.Text;</p>
<p>namespace MyTestPlugin<br />
<p> public class Lead<br />
 {<br />
 public string Topic { get; set; }<br />
 public string FullName { get; set; }<br />
 public string Email { get; set; }<br />
<p> public class MyPluginClass : IPlugin<br />
 {<br />
 public void Execute(IServiceProvider serviceProvider)<br />
 {<br />
 try<br />
 {<br />
 // Obtain the execution context from the service provider.<br />
 IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));</p>
<p> // The InputParameters collection contains all the data passed in the message request.<br />
 if (context.InputParameters.Contains("Target") &amp;&amp; context.InputParameters["Target"] is Entity)<br />
 {<br />
 // Obtain the target entity from the input parameters.<br />
 Entity entity = (Entity)context.InputParameters["Target"];</p>
<p> using (WebClient client = new WebClient())<br />
 {<br />
 var myLead = new Lead();<br />
 myLead.Topic = entity.Attributes["subject"].ToString();<br />
 myLead.FullName = entity.Attributes["fullname"].ToString();<br />
 myLead.Email = entity.Attributes["emailaddress1"].ToString();</p>
<p> DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Lead));<br />
 MemoryStream memoryStream = new MemoryStream();<br />
 serializer.WriteObject(memoryStream, myLead);<br />
 var jsonObject = Encoding.Default.GetString(memoryStream.ToArray());</p>
<p> var webClient = new WebClient();<br />
 webClient.Headers[HttpRequestHeader.ContentType] = "application/json";<br />
 var code = "key";<br />
 var serviceUrl = "" + code;</p>
<p> // upload the data using Post mehtod<br />
 string response = webClient.UploadString(serviceUrl, jsonObject);<br />
 }<br />
 }<br />
 }<br />
 catch (Exception ex)<br />
 {<br />
 throw new InvalidPluginExecutionException(ex.Message);<br />
 }<br />
 }<br />
 }<br />
}<br />

Hope it helps..


Author: Nishant Rana

I love working in and sharing everything about Microsoft.NET technology !

5 thoughts on “Using WebClient to call external service from CRM Online Sandboxed Plugin (HTTP POST and JSON)”

  1. HTTP requests being issued in plug-ins reviewed where Keep-Alive is not being set to false. Keep-Alive set to true in the HTTP request header can cause delays upwards of 20+ seconds that is sporadic, especially within Microsoft Dynamics 365/CRM Online.

    To set KeepAlive to false use an override implementation of the WebClient similar to…

    internal class MyWebClient : WebClient
    // Overrides the GetWebRequest method and sets keep alive to false
    protected override WebRequest GetWebRequest(Uri address)
    HttpWebRequest req = (HttpWebRequest)base.GetWebRequest(address);
    req.KeepAlive = false;

    return req;

    Liked by 1 person

  2. I have try out the sample, but then with a certificate which is embedded in the API request call, but when i do the request from inside a Plugin in CRM 365 then a security exception appair. Then same exception appair when i use an Activity too in a Workflow. I have try many scenario’s but no-one works as the Plugin and Workflows run in a sandbox instance of CRM 365.
    Do you have a solution to solve my problem?


  3. Hi Nishant ,
    I tried this with late bound crm entity object it gives the following error “The data contract type cannot be serialized in partial trust because the member ‘key’ is not public”.I registered the plugin in sandbox mode.
    How to resolve this?


    1. Hi Nishant, I’ve followed the webclient method within a plugin which is working really good. Thanks for the example above. But with Web Client, Is there any way we can find the status code of the Post call using Web Client?


Please share your thoughts

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.