您可以使用ASP.NET的HttpClient类来将API URL转换为模型对象列表。以下是一个示例代码:
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
public class Program
{
public static async Task Main(string[] args)
{
// 设置API的URL
string apiUrl = "https://api.example.com/objects";
// 创建HttpClient对象
using (HttpClient client = new HttpClient())
{
// 设置请求头部
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
try
{
// 发送GET请求并获取响应
HttpResponseMessage response = await client.GetAsync(apiUrl);
// 确保请求成功
response.EnsureSuccessStatusCode();
// 将响应内容转换为模型对象列表
List models = await response.Content.ReadAsAsync>();
// 使用模型对象列表进行其他操作
foreach (MyModel model in models)
{
Console.WriteLine($"ID: {model.Id}, Name: {model.Name}");
}
}
catch (Exception ex)
{
Console.WriteLine($"请求出现错误: {ex.Message}");
}
}
}
}
public class MyModel
{
public int Id { get; set; }
public string Name { get; set; }
}
在上面的代码中,我们首先创建了一个HttpClient对象,并设置了请求的Accept头部为“application/json”。然后,我们发送一个GET请求到指定的API URL,并获取响应。接下来,我们使用ReadAsAsync方法将响应内容转换为一个List