简体   繁体   English

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

[英]How to POST data in Dynamics 365 using HttpWebRequest

I have requirement to read data from Dynamics 365 online and to write data as well. 我需要在线从Dynamics 365中读取数据并也要写入数据。

Since my application Target Framework is .Net Core 2.1 so I am unable to use Microsoft.Xrm.Sdk and decided to use Web api instead. 由于我的应用程序目标框架是.Net Core 2.1,所以我无法使用Microsoft.Xrm.Sdk,而是决定使用Web api。

In my code I am using HttpWebRequest with "GET" and "POST" methods, the GET operation works fine and am able to retrieve records from D365 using web api. 在我的代码中,我将HttpWebRequest与“ GET”和“ POST”方法一起使用,GET操作可以正常工作,并且能够使用Web API从D365检索记录。 When I use the POST operation the code executes properly without any error but when I navigate to D365 entity I do not see any newly created record. 当我使用POST操作时,代码可以正确执行,没有任何错误,但是当我导航到D365实体时,看不到任何新创建的记录。

Below is my code 下面是我的代码

The GetContactDetailsAsync function works fine and returns result but the CreateCaseAsync function is not working 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) { }

    }

I have tried changing string json = "{\\"title\\":\\"title by chat bot\\"}" to "{'title':'title by chat bot'}" and "{title:title by chat bot}" as well. 我尝试将string json = "{\\"title\\":\\"title by chat bot\\"}"更改为"{'title':'title by chat bot'}""{title:title by chat bot}"

Also I have tried changing Stream requestDataStream = await webRequest.GetRequestStreamAsync(); 我也尝试过更改Stream requestDataStream = await webRequest.GetRequestStreamAsync(); to Stream requestDataStream = webRequest.GetRequestStream(); Stream requestDataStream = webRequest.GetRequestStream(); as well but nothing worked. 同样,但没有任何效果。

Unable to figure out what I am missing in my code. 无法弄清楚我的代码中缺少什么。 Any help is highly appriciated. 高度重视任何帮助。

Actually code looks fine but you should get 400 Bad request exception. 实际上代码看起来不错,但是您应该得到400 Bad Request异常。 Because the json is missing customerid and the basic payload for creating incident should be like below: 由于json缺少customerid并且用于创建事件基本有效负载应如下所示:

{
  "title": "title by chat bot",
  "customerid_account@odata.bind": "/accounts(f686f062-e542-e811-a955-000d3ab27a43)"
}

You can refer this SO thread for clarity. 为了清楚起见,您可以引用此SO线程

Here is the Code for Webapi using Javascript. 这是使用Javascript的Webapi代码。 I just tried below code in my Org and it worked for me. 我只是在组织中尝试下面的代码,它对我有用。

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));

and Below is the link where you could find exactly how to use PATCH method for CRM using c# 在下面的链接中,您可以确切地找到如何使用c#将PATCH方法用于CRM的方法

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

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

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