创建 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 callvar 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 callConsole.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; }} }
运行程序
查看控制台应用程序窗口。输出应如下所示: