我需要在线从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();
但没有任何效果。
无法弄清楚我的代码中缺少什么。高度重视任何帮助。
答案 0 :(得分:0)
实际上,代码看起来不错,但是您应该得到400 Bad Request异常。由于json缺少customerid
,而basic payload for creating incident应该如下所示:
{
"title": "title by chat bot",
"customerid_account@odata.bind": "/accounts(f686f062-e542-e811-a955-000d3ab27a43)"
}
为清楚起见,您可以参考此SO thread。
答案 1 :(得分:0)
这是使用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#准确使用CRM的PATCH方法的方法