簡體   English   中英

如何使用HttpWebRequest在Dynamics 365中發布數據

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

我需要在線從Dynamics 365中讀取數據並也要寫入數據。

由於我的應用程序目標框架是.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(); 同樣,但沒有任何效果。

無法弄清楚我的代碼中缺少什么。 高度重視任何幫助。

實際上代碼看起來不錯,但是您應該得到400 Bad Request異常。 由於json缺少customerid並且用於創建事件基本有效負載應如下所示:

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

為了清楚起見,您可以引用此SO線程

這是使用Javascript的Webapi代碼。 我只是在組織中嘗試下面的代碼,它對我有用。

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/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