简体   繁体   中英

How to post data to Dynamics CRM in C# using Access Token

I need to post data from an MVC form to our Dynamics CRM, I've got the function setup which gets an Access Token, but I don't know how to then use it to send the data to CRM. I'm able to post and create records in CRM via Postman, but I don't know how to marry the Access Token and the Postman post together in C#.

Acquiring Access Token:

string organizationUrl = "https://myorgcrm.crm4.dynamics.com";
string appKey = "XXXXXXxxxXxXXXxXXXXXX+XXxxxxXXxxxXXxxxXXXXX=";
string aadInstance = "https://login.microsoftonline.com/";
string tenantID = "myorg.onmicrosoft.com";
string clientId = "XXXXX-XXXX-XXXX-XXXX-XXXXXXXXXX";   

public string AuthenticateWithCRM()
{ 
    AuthenticationContext authContext = new AuthenticationContext("https://login.windows.net/common", false);

    ClientCredential clientcred = new ClientCredential(clientId, appKey);
    AuthenticationContext authenticationContext = new AuthenticationContext(aadInstance + tenantID);
    AuthenticationResult authenticationResult = authenticationContext.AcquireTokenAsync(organizationUrl, clientcred).Result;

    return authenticationResult.AccessToken;
}

This returns an Access Token, because it returns a token I'm assuming this is correct, but until I know how to try to send data I've been unable to know for sure.

Postman Post....

JSON:

{
    "org_accountnumber": '12345',
    "org_Individualid":
    {
        "firstname": "Luke",
        "lastname": "Skywalker"
    },
    "orgstuff@odata.bind":"/orgstuff_schemes(XXXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXX)"
}

I run this with an access token filling in Auth URL, Access Token URL, and Client ID, it then works based on my work windows user account.

Not that familiar with Dynamics CRM but from what I found on the MS DOCS it seems familiar.

Normally you'd request the accessToken as you have, when an user logs into your application, or when your application bootstraps. According to OAuth you will have to pass the accesstoken as a header on any request. To do this in C#

using (HttpClient httpClient = new HttpClient())
{
    httpClient.Timeout = new TimeSpan(0, 2, 0);  // 2 minutes
    httpClient.DefaultRequestHeaders.Authorization = 
        new AuthenticationHeaderValue("Bearer", result.AccessToken);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM