How can I read result of web api call from Dynamics 365?

1k Views Asked by At

I try to retrieve a record from Dynamics 365 Sales. I created an app registration in Azure and I can get tokens based on this app.

Also, I can call the HTTP client. But I couldn't figure out how to read the result of the HTTP call.

Microsoft published only WhoAmIRequest sample, but I couldn't find a sample of other entities.

Here is my sample code. I try to read body object.

try
{
    string serviceUrl = "https://****.crm4.dynamics.com/";
    string clientId = "******";
    string clientSecret = "*******";
    string tenantId = "*******";

    A***.Library.Utility.MSCRM mscrm = new Library.Utility.MSCRM(serviceUrl, clientId, clientSecret, tenantId);
    var token = await mscrm.GetTokenAsync();

    Console.WriteLine(token);

    using (HttpClient client = new HttpClient())
    {
        client.BaseAddress = new Uri(serviceUrl);
        client.Timeout = new TimeSpan(0, 2, 0);  //2 minutes  
        client.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
        client.DefaultRequestHeaders.Add("OData-Version", "4.0");
        client.DefaultRequestHeaders.Accept.Add(
                        new MediaTypeWithQualityHeaderValue("application/json"));

        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "/api/data/v9.0/accounts");

        // Set the access token
        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);

        HttpResponseMessage response = client.SendAsync(request).Result;

        if (response.IsSuccessStatusCode)
        {
            // Get the response content and parse it.  
            var responseStr = response.Content.ReadAsStringAsync();

            JObject body = JObject.Parse(response.Content.ReadAsStringAsync().Result);
        }
    }
}
catch(Exception e)
{
    Console.WriteLine(e.Message);
}

Here is the result of body object.

enter image description here

1

There are 1 best solutions below

1
On BEST ANSWER

You can use either of these syntax to read values. Read more

JObject body = JObject.Parse(response.Content.ReadAsStringAsync().Result);

// Can use either indexer or GetValue method (or a mix of two)
body.GetValue("obs_detailerconfigid");
body["obs_detailerconfigid"];