Click here to Skip to main content
15,893,588 members
Articles / Enterprise

Using the Microsoft Dynamics CRM Online Web API From Your ASP.NET MVC Website

Rate me:
Please Sign up or sign in to vote.
2.33/5 (2 votes)
29 Aug 2016CPOL 12.7K   1   2
How to use the Microsoft Dynamics CRM Online Web API from your ASP.NET MVC website

The Microsoft 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 a Microsoft 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.

C#
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);
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect BlackBall Software
New Zealand New Zealand
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionError. Please help Pin
Member 1348611224-Jan-19 1:10
Member 1348611224-Jan-19 1:10 
QuestionCool Pin
gtezini26-Dec-16 3:32
gtezini26-Dec-16 3:32 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.