Dynamics CRM 365 Web API 入门
创建 Visual Studio 项目
- 启动 Visual Studio 2022,然后选择“创建新项目”。
- 创建新的控制台应用项目。
- 通过设置“位置”和“项目名称”来配置项目。
- 通过选择“.NET 8.0(长期支持)”和“不使用顶级语句”来配置项目。然后单击“创建”。
编辑Program.cs
按照以下后续步骤为主程序添加代码。
-
将
Program.cs
替换为以下代码。using System.Net; using System.Text.Json; namespace WebAPIQuickStart { internal class Program { static async Task Main() { string userName = ""; string password = ""; string domainName = ""; string webAPIBaseAddress = "https://<env-name>/D365/api/data/v9.1/";//修改环境地址 HttpClient client = GetNewHttpClient(userName, password, domainName, webAPIBaseAddress); #region Web API call var response = await client.GetAsync("WhoAmI"); if (response.IsSuccessStatusCode) { Guid userId = new(); string jsonContent = await response.Content.ReadAsStringAsync(); // Using System.Text.Json //using (JsonDocument doc = JsonDocument.Parse(jsonContent)) //{ // JsonElement root = doc.RootElement; // JsonElement userIdElement = root.GetProperty("UserId"); // userId = userIdElement.GetGuid(); //} // Alternate code, but requires that the WhoAmIResponse class be defined (see below). WhoAmIResponse whoAmIresponse = JsonSerializer.Deserialize<WhoAmIResponse>(jsonContent); userId = whoAmIresponse.UserId; Console.WriteLine($"Your user ID is {userId}"); } else { Console.WriteLine("Web API call failed"); Console.WriteLine("Reason: " + response.ReasonPhrase); } #endregion Web API call Console.ReadKey(); } private static HttpClient GetNewHttpClient(string userName, string password, string domainName, string webAPIBaseAddress) { HttpClient client = new HttpClient(new HttpClientHandler() { Credentials = new NetworkCredential(userName, password, domainName) }); client.BaseAddress = new Uri(webAPIBaseAddress); client.Timeout = new TimeSpan(0, 2, 0); return client; } } /// <summary> /// WhoAmIResponse class definition /// </summary> /// <remarks>To be used for JSON deserialization.</remarks> public class WhoAmIResponse { public Guid BusinessUnitId { get; set; } public Guid UserId { get; set; } public Guid OrganizationId { get; set; } } }
运行程序
查看控制台应用程序窗口。输出应如下所示:
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· 【.NET】调用本地 Deepseek 模型
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
· 上周热点回顾(2.17-2.23)