在向大家介绍了两篇比较概念化的文章后,我们今天来看看一些具体的Web API编程实例吧,在本文中,我讲向大家介绍怎么在重客户端下面调用CRM Web API完成基本的CRUD操作。 什么是重客户端呢?哈哈,这个词是我自己发明的,用了表示那些非浏览器脚本的API消费者,例如:使用C#代码做的数据接口,中间服务等。
那么重客户端和那些轻客户端(浏览器脚本)有什么本质的区别吗?就我来看,最大的区别莫过于在重客户端编程我们需要考虑API的验证与授权部分,但是在轻客户端,我们则不需要。使用过Dynamics CRM里面使用过REST接口进行编程的同学可能已经意识到,如果我们仅仅在浏览器脚本(不涉及跨域)上调用API,我们是不需要涉及任何权限验证和授予的过程。
在重客户端中使用Web API对CRM进行事务操作,一共有两个难点:其一,需要构造JSON格式的输入参数,其二,需要构造符合规则的Odata URL。对于前者,我们可以使用JSON序列化类库进行操作,至于后者,我们可以参考官方的SDK进行URL的构造。
在进行编程前,首先保证你的项目里面已经引用了如下的类库,如果没有,可以使用NuGet进行安装(搜索ID名称,例如:Newtonsoft.Json)
<?xml version="1.0" encoding="utf-8"?> <packages> <package id="Microsoft.IdentityModel.Clients.ActiveDirectory" version="2.19.208020213" targetFramework="net452" /> <package id="Newtonsoft.Json" version="7.0.1" targetFramework="net452" /> <package id="System.Net.Http" version="2.0.20126.16343" targetFramework="net452" /> <package id="System.Net.Http.Formatting.Extension" version="5.2.3.0" targetFramework="net452" /> </packages>
在进行具体的功能实现前,大家需要使用上篇博文中的验证辅助类来生成AccessToken,然后我们才能进行具体的业务实现。
首先,我们生成AccessToken,然后将其赋给HttpClient对象,这样服务器才能识别该次请求为授权请求,下面的代码片段是对Account进行Create操作
Authentication auth = new Authentication(clientId, service, redirectUrl, username, password); //create an account JObject acc = new JObject(); acc.Add("name", "this account was created by WEB API"); HttpRequestMessage createReq = new HttpRequestMessage(HttpMethod.Post, string.Format("api/data/accounts")); createReq.Content = new StringContent(JsonConvert.SerializeObject(acc), Encoding.UTF8, "application/json"); createReq.Headers.Authorization = new AuthenticationHeaderValue("Bearer", auth.AcquireToken().AccessToken); HttpResponseMessage createResponse = await client.SendAsync(createReq).ConfigureAwait(false); string accountUri = string.Empty; if (createResponse.IsSuccessStatusCode) { var result = await createResponse.Content.ReadAsStringAsync(); accountUri = createResponse.Headers.GetValues("OData-EntityId").FirstOrDefault(); }
//read an account if (!string.IsNullOrEmpty(accountUri)) { HttpRequestMessage getReq = new HttpRequestMessage(HttpMethod.Get, accountUri); getReq.Headers.Authorization = new AuthenticationHeaderValue("Bearer", auth.AcquireToken().AccessToken); HttpResponseMessage getResp = await client.SendAsync(getReq); if (getResp.IsSuccessStatusCode) { JObject retrievedAcc = JsonConvert.DeserializeObject<JObject>(await getResp.Content.ReadAsStringAsync()); if (retrievedAcc != null) { Console.WriteLine(retrievedAcc["name"]); } } }
//update an account if (!string.IsNullOrEmpty(accountUri)) { HttpRequestMessage uptReq = new HttpRequestMessage(new HttpMethod("PATCH"), accountUri); JObject uptAcc = new JObject(); uptAcc.Add("telephone1", "12345"); //text uptAcc.Add("[email protected]", "https://server/api/data/contacts(d870721c-bf64-e511-80f0-c4346bc43f98)"); //lookup uptAcc.Add("donotemail", false); //bool uptAcc.Add("address1_shippingmethodcode", 3); //optionset uptAcc.Add("new_testcurrency", 500.51); uptAcc.Add("new_testdecimal", 1000.1); uptAcc.Add("new_testfloat", 2000.2); uptAcc.Add("new_testtime", DateTime.Now); uptAcc.Add("new_testwholenumber", 5000); uptReq.Headers.Authorization = new AuthenticationHeaderValue("Bearer",auth.AcquireToken().AccessToken); uptReq.Content = new StringContent(JsonConvert.SerializeObject(uptAcc), Encoding.UTF8, "application/json"); HttpResponseMessage uptResp = await client.SendAsync(uptReq); if (uptResp.IsSuccessStatusCode) { Console.WriteLine("Update Successfully"); } }
//delete an account if (!string.IsNullOrEmpty(accountUri)) { HttpRequestMessage delReq = new HttpRequestMessage(HttpMethod.Delete, accountUri); delReq.Headers.Authorization = new AuthenticationHeaderValue("Bearer", auth.AcquireToken().AccessToken); HttpResponseMessage delResp = await client.SendAsync(delReq); if (delResp.IsSuccessStatusCode) { Console.WriteLine("Delete Successfully"); } }