Dynamics CRM 使用web api更新记录

Posted on 2022-01-18,2 min read

使用如下方式实现Patch

HttpRequestMessage request = new HttpRequestMessage(new HttpMethod("Patch"), "/api/data/v9.2/accounts(b6a19cdd-88df-e311-b8e5-6c3be5a8b200)")

private static async Task webApiTest()
{
    try
    {
        var accessToken = await webAPIClientCredMethod();
        JObject account1 = new JObject{
                { "name", "Coffee" },
                { "emailaddress1", "best@123.com" }
            };
        account1.Add("ownerid@odata.bind", "systemusers(0f487f58-936f-ec11-8943-000d3a827eb5)");

        using (HttpClient client = new HttpClient())
        {
            client.BaseAddress = new Uri("https://org639ab8b4.crm5.dynamics.com");
            client.Timeout = new TimeSpan(0, 2, 0);  //2 minutes  
            client.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
            client.DefaultRequestHeaders.Add("OData-Version", "4.0");
            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));
            HttpRequestMessage request =
                new HttpRequestMessage(new HttpMethod("Patch"), "/api/data/v9.2/accounts(b6a19cdd-88df-e311-b8e5-6c3be5a8b200)")
                {
                    Content = new StringContent(account1.ToString(), Encoding.UTF8, "application/json")
                };
            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            HttpResponseMessage response = client.SendAsync(request).Result;
            // if (response.IsSuccessStatusCode)
            if (response.StatusCode == HttpStatusCode.NoContent)
            {
                var entityUri = response.Headers.GetValues("odata-entityid").FirstOrDefault();
                Console.WriteLine("a new account was created successfully: " + entityUri);
                Console.WriteLine("Done!");
                Console.ReadKey();
            }
            else
            {
                Console.WriteLine(response);
                Console.ReadKey();
            }
        }
    }
    catch (Exception e)
    {
        Console.WriteLine("An error occurred for webApiTest:\n " + e.Message);
        Console.ReadKey();
    }
}

下一篇: 再也不用58同城了→