如何使用HttpWebRequest在Dynamics 365中发布数据

问题描述 投票:1回答:2

我需要在线读取Dynamics 365的数据并写入数据。

由于我的应用程序Target Framework是.Net Core 2.1,因此我无法使用Microsoft.Xrm.Sdk并决定使用Web api。

在我的代码中,我使用HttpWebRequest和“GET”和“POST”方法,GET操作正常,并且能够使用web api从D365检索记录。当我使用POST操作时,代码正确执行而没有任何错误,但是当我导航到D365实体时,我没有看到任何新创建的记录。

以下是我的代码

GetContactDetailsAsync函数工作正常并返回结果但CreateCaseAsync函数不起作用

public static async Task<string> GetContactDetailsAsync()
{
 string organizationUrl = "https://xxxxx.crmX.dynamics.com";
 string clientId = "xxxxxxxx-73aa-xxxx-94cc-8dc7941f6600";
 string appKey = "Xxxx81H/7TUFErt5C/xxxxxxxxxxxxxxxxxxxxxxx=";
 string aadInstance = "https://login.microsoftonline.com/";
 string tenantID = "xxxxxxxx.onmicrosoft.com";

        try
        {
            ClientCredential clientcred = new ClientCredential(clientId, appKey);
            AuthenticationContext authenticationContext = new AuthenticationContext(aadInstance + tenantID);

            AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenAsync(organizationUrl, clientcred);
            var requestedToken = authenticationResult.AccessToken;

            var webRequest = (HttpWebRequest)WebRequest.Create(new Uri("https://xxxxxxxxxx.api.crmx.dynamics.com/api/data/v9.1/contacts()?$select=fullname,contactid,emailaddress1&$filter=mobilephone eq '"+History.userMobile+"'"));
            webRequest.KeepAlive = false;
            webRequest.ServicePoint.ConnectionLimit = 1;

            webRequest.Method = "GET";
            webRequest.ContentLength = 0;
            webRequest.Headers.Add("Authorization", String.Format("Bearer {0}", requestedToken));
            webRequest.Headers.Add("OData-MaxVersion", "4.0");
            webRequest.Headers.Add("OData-Version", "4.0");
            webRequest.Accept = "application/json";
            webRequest.ContentType = "application/json";

            //if contact with user provided phone number found, ask for problem description
            try
            {
                using (var response1 = webRequest.GetResponse() as System.Net.HttpWebResponse)
                {
                    using (var reader = new System.IO.StreamReader(response1.GetResponseStream()))
                    {
                        var response = reader.ReadToEnd();
                    }
                }
            }
            catch (Exception ex)
            {
                History.isUserFound = false;
                string error = ex.Message;
                return "Sorry, I found that you are not using any of our services...";
            }
        }
        catch (Exception ex) { return ex.ToString(); }

    }




public static async void CreateCaseAsync()
        {
 string organizationUrl = "https://xxxxx.crmX.dynamics.com";
 string clientId = "xxxxxxxx-73aa-xxxx-94cc-8dc7941f6600";
 string appKey = "Xxxx81H/7TUFErt5C/xxxxxxxxxxxxxxxxxxxxxxx=";
 string aadInstance = "https://login.microsoftonline.com/";
 string tenantID = "xxxxxxxx.onmicrosoft.com";

        //trying to establish connection with D365 here
        try
        {
            ClientCredential clientcred = new ClientCredential(clientId, appKey);
            AuthenticationContext authenticationContext = new AuthenticationContext(aadInstance + tenantID);

            AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenAsync(organizationUrl, clientcred);
            var requestedToken = authenticationResult.AccessToken;

            var webRequest = (HttpWebRequest)WebRequest.Create(new Uri("https://xxxxxxxx.api.crmx.dynamics.com/api/data/v9.1/incidents"));
            webRequest.KeepAlive = false;
            webRequest.ServicePoint.ConnectionLimit = 1;

            webRequest.Method = "POST";
            webRequest.Headers.Add("Authorization", String.Format("Bearer {0}", requestedToken));
            webRequest.Headers.Add("OData-MaxVersion", "4.0");
            webRequest.Headers.Add("OData-Version", "4.0");
            webRequest.Accept = "application/json";
            webRequest.ContentType = "application/json";

            string json = "{\"title\":\"title by chat bot\"}";
            byte[] byteArray;
            byteArray = Encoding.UTF8.GetBytes(json);
            webRequest.ContentLength = byteArray.Length;

            try
            {
                Stream requestDataStream = await webRequest.GetRequestStreamAsync();
                requestDataStream.Write(byteArray, 0, byteArray.Length);
                requestDataStream.Close();
            }
            catch (Exception ex) { }
        }

        catch (Exception ex) { }

    }

我曾尝试将string json = "{\"title\":\"title by chat bot\"}"改为"{'title':'title by chat bot'}""{title:title by chat bot}"

我也尝试过将Stream requestDataStream = await webRequest.GetRequestStreamAsync();改为Stream requestDataStream = webRequest.GetRequestStream();,但没有任何效果。

无法弄清楚我的代码中缺少什么。任何帮助都是高度关注的。

c# .net-core dynamics-crm microsoft-dynamics
2个回答
0
投票

实际上代码看起来很好但你应该得到400 Bad请求异常。因为json缺少customerid而且basic payload for creating incident应该如下所示:

{
  "title": "title by chat bot",
  "[email protected]": "/accounts(f686f062-e542-e811-a955-000d3ab27a43)"
}

为清晰起见,您可以参考此SO thread


0
投票

这是使用Javascript的Web Api代码。我只是在我的组织中尝试下面的代码,它对我有用。

var entity = {};
entity.title = "CCCCAAAASSSEEEE";

var req = new XMLHttpRequest();
req.open("PATCH", Xrm.Page.context.getClientUrl() + "/api/data/v9.1/incidents(BA8BC3CD-D94F-E911-A82F-000D3A385A1C)", true);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.onreadystatechange = function() {
    if (this.readyState === 4) {
        req.onreadystatechange = null;
        if (this.status === 204) {
            //Success - No Return Data - Do Something
        } else {
            Xrm.Utility.alertDialog(this.statusText);
        }
    }
};
req.send(JSON.stringify(entity));

以下是您可以使用c#找到如何使用PATCH方法进行CRM的链接

https://docs.microsoft.com/en-us/dynamics365/customer-engagement/developer/webapi/web-api-functions-actions-sample-csharp

© www.soinside.com 2019 - 2024. All rights reserved.