Using the Microsoft Dynamics CRM Online Web API from your ASP.Net MVC website

Using the Microsoft Dynamics CRM Online Web API from your ASP.Net MVC website

The MS Dynamics Web API has a lot of promise, allowing users to authenticate using OAuth2 then granting your application access to their CRM data.  Unfortunately, the documentation provided by Microsoft is misleading at best.

After bashing my head against the wall for about ten hours, I got a response back from an MS developer with the following working solution, which I’ve padded-out and am sharing here to hopefully save somebody else the headache.

Here’s the working code sample, just drop in as a standard ActionResult in your MVC project – no other code is required/involved.

public async Task<ActionResult> GetAccountsFromDynamics()
{// Once you've created your Native Client in Azure AD, you can get the clientID for it
var azureTenantGuid = "***";
var clientID = "***";
var tokenRequestUrl = string.Format(@"https://login.microsoftonline.com/{0}/oauth2/token", azureTenantGuid);
// The credentials for the CRM *user* that you are accessing CRM on behalf of
var crmUrl = "https://your_crm_url.dynamics.com";
var userName = "***";
var password = "***";

// Connect to the authentication server
var request = (HttpWebRequest)WebRequest.Create(tokenRequestUrl);
request.Method = "POST";

// Write our request to the request body
using (var reqStream = await request.GetRequestStreamAsync())
{
var postData = string.Format(@"client_id={0}&resource={1}&username={2}&password={3}&grant_type=password", clientID, crmUrl, userName, password);
var postBytes = new ASCIIEncoding().GetBytes(postData);
reqStream.Write(postBytes, 0, postBytes.Length);
reqStream.Close();
}

// Call the authentication server and parse out the response
var accessToken = "";
using (var response = (HttpWebResponse)request.GetResponse())
{
// Proceed interpreting result
var dataStream = response.GetResponseStream();
if (dataStream != null)
{
var reader = new StreamReader(dataStream);

// The response is returned as JSON, these lines just conver it to a C# object. The format includes our access token:
// Example format: {access_Token: "abc...", scope: "public"}
var json = reader.ReadToEnd();

var tokenSummary = json.FromJson<TokenSummary>();
accessToken = tokenSummary.access_token;
}
}

// Now make a request to Dynamics CRM, passing in the toekn
var apiBaseUrl = "https://your_crm_url.dynamics.com/api/data/v8.1/";
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var result = await httpClient.GetAsync(apiBaseUrl + "accounts?$select=name&$top=3");
var accountInfoJson = await result.Content.ReadAsStringAsync();

// You're done!
return Content(accountInfoJson);
}
How to easily bind VueJS to a Typescript or ES6 class

How to easily bind VueJS to a Typescript or ES6 class

Read our new book – How to know if your software developer is trying to kill you

Read our new book – How to know if your software developer is trying to kill you