I was working on the integration between Dataverse and external Rest API. The scenario is simple as – “Send the JSON object to the API when the record is created”. In order to implement this, I decided to develop the plugin that will get the data from the context, transform it to the proper JSON object, and using HttpWebRequest/HttpWebResponse – perform the communication with the external API.
I built the console app in order to test that code works fine before moving the code to the plugin and it looked like the following:
var request = HttpWebRequest.Create("https://supersecret.api/api"); request.Method = "POST"; request.ContentType = "application/json"; request.Headers["Accept"] = "application/json"; var payloadObject = new PayloadObject(); //Setting properties of Payload Object here var payloadObjectData = Serialize<PayloadObject>(payloadObject); using (var sw = request.GetRequestStream()) { sw.Write(payloadObjectData, 0, payloadObjectData.Length); sw.Close(); } string responseContent; try { using (var sr = new StreamReader(request.GetResponse().GetResponseStream())) { responseContent = sr.ReadToEnd(); } var response = Deserialize<Response>(responseContent); //Handling of the response here } catch (WebException e) { string errorMessage; using (var sr = new StreamReader(e.Response.GetResponseStream())) { errorMessage = sr.ReadToEnd(); } //Handling of an error here }
Code worked fine and did what it should with no issues. But when I moved this code to the plugin I immediately got “The ‘Accept’ header must be modified using the appropriate property or method. Parameter name: name” error during the first run. After a few experiments and variations of the code following change fixed the issue:
var request = (HttpWebRequest)HttpWebRequest.Create("https://supersecret.api/api"); request.Method = "POST"; request.ContentType = "application/json"; request.Accept = "application/json";