Use Dynamics 365 WEB API in Azure Functions Version 3

In the previous post, we saw how to authenticate Dynamics 365 in Azure Functions runtime version 3 (.NET Core). Now let’s see how to use Dynamics 365 WEB API after acquiring the bearer token.

The following sample code accepts email as input in the request body, and uses Web api to return the contacts records with the passed email.

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Net.Http;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System.Net;
using System.Net.Http.Headers;

namespace SampleFunctionApp
{
   

    public static class D365
    {
        [FunctionName("ConnecttoD365")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            string contactEmail = req.Query["email"];
            string responseMessage = string.Empty;
            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data = JsonConvert.DeserializeObject(requestBody);
            contactEmail = contactEmail ?? data?.email;
            #region Auth Code
            //
            string cloud = "https://login.microsoftonline.com";

            //This is the Domain!

            string tenantId = "*******";

            string authority = $"{cloud}/{tenantId}";

            // ApplicationID in the new UI

            string clientId = "************";

            //Created from scratch in Keys

            string clientsecret = "*************";

            ClientCredential clientcred = new ClientCredential(clientId, clientsecret);

            // Application ID of the Resource (could also be the Resource URI)

            string resource = "https://*****.crm.dynamics.com/";

            AuthenticationContext ac = new AuthenticationContext(authority);
            AuthenticationResult result = null;
            var bearerToken = string.Empty;
            string ErrorMessege = string.Empty;
            try

            {
                //already having token
                result = await ac.AcquireTokenSilentAsync(resource, clientId);
                if (result != null)
                {
                    bearerToken = result.AccessToken;
                    log.LogInformation("Token Acquired:" );
                }
            }

            catch (AdalException adalException)

            {//Acquire token
                if (adalException.ErrorCode == AdalError.FailedToAcquireTokenSilently

                || adalException.ErrorCode == AdalError.InteractionRequired)

                {

                    result = await ac.AcquireTokenAsync(resource, clientcred);
                    if (result != null)
                    {
                        bearerToken = result.AccessToken;
                        log.LogInformation("Token Acquired");

                    }
                }
                else
                {
                    log.LogWarning("Failed to acquire Bearer Token :-" + adalException.Message);
                    var AdalException = new { adalexception = "Failed to acquire Bearer Token :-" + adalException.Message };
                    return new BadRequestObjectResult(JsonConvert.SerializeObject(AdalException));
                    throw adalException;

                }

            }

            #endregion

            #region getContact
           


            string outputString = string.Empty;
            //Next use a HttpClient object to connect to specified CRM Web service.
            var httpClient = new HttpClient();
            //Define the Web API base address, the max period of execute time, the 
            // default OData version, and the default response payload format.
            httpClient.BaseAddress = new Uri("https://*********.crm.dynamics.com/api/data/v9.1/");
            httpClient.Timeout = new TimeSpan(0, 2, 0);
            httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
            httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");
            httpClient.DefaultRequestHeaders.Add("Prefer", "odata.include-annotations=\"*\"");
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", (bearerToken));

            //Query to retrieve contacts
            var queryOptions = "contacts?$select=fullname,mobilephone&$filter=emailaddress1 eq '" + contactEmail + "'";
            HttpResponseMessage retrieveResponse1 = httpClient.GetAsync(queryOptions).Result;


            if (retrieveResponse1.StatusCode == HttpStatusCode.OK)
            {


              

                    responseMessage = retrieveResponse1.Content.ReadAsStringAsync().Result.ToString();
               

            }
            else
            {

                return new BadRequestObjectResult(JsonConvert.SerializeObject("an error occured while retriving contacts"));
            }



            #endregion

            if (string.IsNullOrEmpty(contactEmail) && responseMessage== String.Empty)
            {
                responseMessage = "Pass an email in the query string or in the request body";
            }        

            return new OkObjectResult(responseMessage);
        }
    }
}

Test your function from post man.

Request
Response

Please note, the response in the code is not well formatted, you may format the response as a proper json object based on your business need.

Hope this helps.

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 )

Facebook photo

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

Connecting to %s