MS Dynamics 365 – Consume Dynamics Web API from C#

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

Reference URL :

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 = "";
private static string redirectUrl = "";
private const string Authority = "<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;
AuthenticationContext authContext = new AuthenticationContext(Authority, false);
UserCredential cred = new UserPasswordCredential(userName, password);

result = await authContext.AcquireTokenAsync(serviceUri, clientId, cred);
catch (Exception ex)
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