MS Dynamics 365 – Consume Dynamics Web API from C#

Ankaprasad
Posted by Ankaprasad under C# category on | Points: 40 | Views : 2089
1. Register an application with Azure Active directory.

Reference URL : https://docs.microsoft.com/en-us/powerapps/developer/common-data-service/walkthrough-register-app-azure-active-directory

2. Copy “Client Id” and “Tenant Id”

3. Create Console application and add “Microsoft.IdentityModel.Clients.ActiveDirectory” from Nuget package manager.

4. Add the constants in configuration file or class. Refer the below code to get authentication token from azure AD.

       private static string serviceUri = "https://xyka12.crm.dynamics.com/";
private static string redirectUrl = "https://xyka12.api.crm.dynamics.com/api/data/v9.1/";
private const string Authority = "https://login.microsoftonline.com/<TenantID>"; // Tenant Id after app registration
private const string clientId = "<ClientID>"; // Client ID after app registration
private const string userName = "<User Name>"; // Dynamics 365 user name
private const string password = "<Password>"; // Dynamics 365 user password

static void Main(string[] args)
{
string bearerToken = Task.Run(async () => await GetAuthToken()).Result; // Get bearer token
RetrieveAccounts(bearerToken); // Retrive accounts
}
public static async Task<string> GetAuthToken()
{
AuthenticationResult result = null;
try
{
AuthenticationContext authContext = new AuthenticationContext(Authority, false);
UserCredential cred = new UserPasswordCredential(userName, password);

result = await authContext.AcquireTokenAsync(serviceUri, clientId, cred);
}
catch (Exception ex)
{
throw;
}
return result.AccessToken;
}


5. Read data from Dynamics CRM using the above authentication token and Dynamics CRM Web API.


public static void RetrieveAccounts(string authToken)
{
HttpClient httpClient = null;
httpClient = new HttpClient();
//Default Request Headers needed to be added in the HttpClient Object
httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

//Set the Authorization header with the Access Token received specifying the Credentials
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);

httpClient.BaseAddress = new Uri(redirectUrl);
var response = httpClient.GetAsync("accounts?$select=name&$top=5").Result;
if (response.IsSuccessStatusCode)
{
var accounts = response.Content.ReadAsStringAsync().Result;
}
}

Comments or Responses

Login to post response