简体   繁体   English

如何使用访问令牌将数据发布到C#中的Dynamics CRM中

[英]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. 我需要将数据从MVC表单发布到我们的Dynamics CRM,我已经获得了获取访问令牌的功能设置,但是我不知道如何使用它来将数据发送到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#. 我可以通过Postman在CRM中发布和创建记录,但是我不知道如何在C#中将Access Token和Postman发布结合在一起。

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: 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. 我使用在身份验证URL,访问令牌URL和客户端ID中填写的访问令牌运行此文件,然后它根据我的工作Windows用户帐户运行。

Not that familiar with Dynamics CRM but from what I found on the MS DOCS it seems familiar. Dynamics CRM并不熟悉,但是从MS DOCS上发现它似乎很熟悉。

Normally you'd request the accessToken as you have, when an user logs into your application, or when your application bootstraps. 通常,当用户登录到您的应用程序或应用程序引导时,您通常会请求accessToken。 According to OAuth you will have to pass the accesstoken as a header on any request. 根据OAuth,您必须在任何请求中将accesstoken作为标头传递。 To do this in C# 在C#中做到这一点

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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