【问题标题】:Return List from a web API in C# [duplicate]从 C# 中的 Web API 返回列表 [重复]
【发布时间】:2022-02-23 22:01:04
【问题描述】:

tl;dr:我有一个在浏览器中工作的 API,但我不知道如何返回项目列表,以便在列表中遍历它们。

长版: 我还在为 API 苦苦挣扎,现在又遇到了另一个障碍。我的 API 中有以下代码:

[Route("api/[controller]")]
    [ApiController]
    public class ScheduleController : Controller
    {
        [HttpGet]
        public IEnumerable<Schedule> GetAllSchedules()
        {
            using (ScheduleDataEntities entities = new ScheduleDataEntities())
            {
                return entities.Schedule.ToList();
            }
        }
        [HttpGet("{id}")]
        public Schedule GetIndividualSchedule(int id)
        {
            using (ScheduleDataEntities entities = new ScheduleDataEntities())
                return entities.Schedule.FirstOrDefault(e => e.ScheduleID == id);
        }
    }

当我导航到我的本地主机 (https://localhost:7017/api/schedule) 时,它会很好地返回数据:

[{"userID":121,"weekDay":"Monday","startTime":"07:00:00","endTime":"07:15:00","createdDate":"2022-01-18T22:11:34.8966667","modifiedDate":"2022-01-18T22:11:34.8966667","active":false,"scheduleID":14414,"dayOfWeek":1,"tsType":"Normal"},
{"userID":94,"weekDay":"Wednesday","startTime":"08:45:00","endTime":"09:00:00","createdDate":"2021-11-03T13:50:50.26","modifiedDate":"2021-11-03T13:50:50.26","active":false,"scheduleID":13160,"dayOfWeek":3,"tsType":"Normal"}
...]

到目前为止,一切都很好。现在,我想将列表返回给调用 API 的客户端。我制作了一个简单的测试客户端,当我按下按钮时应该会得到列表:

client.Dispose();
client = new HttpClient();
client.BaseAddress = new Uri("https://localhost:7017/api/schedule/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

List<Schedule> list = GetScheduleList("https://localhost:7017/api/schedule");
//Do something with the list...

但是,我不知道这个方法应该如何工作:

static List<Schedule> GetScheduleList(string path)
{
    List<Schedule> schedules = null;
    HttpResponseMessage response = client.GetAsync(path);
    return schedules;
}

我可以在网上找到的每个教程都说要使用 GetAsync。但是,这只适用于 await 关键字。添加 await 关键字意味着我必须将 async 关键字添加到我的方法中,这意味着我必须返回一个 Task 或类似任务的类型,它不能转换为 List。如果我将其作为任务返回,我该如何将其分解回我的计划列表中?

我真的觉得我已经尝试过我遇到的任何事情,因此非常感谢您提供的任何帮助。

【问题讨论】:

  • 你需要json反序列化
  • 您的 GetScheduleList 需要异步,因为您需要在 client.GetAsync 中等待。您还需要调用您的服务来获取时间表,目前它返回 null
  • 如果您使用.NET Core,请使用IHttpClientFactory。见Use IHttpClientFactory to implement resilient HTTP requests

标签: c# .net


【解决方案1】:

试试这个

static async Task<List<Schedule>> GetScheduleList(string path)
{
     var response = await client.GetAsync(path);
    if (response.IsSuccessStatusCode)
    {
        var stringData = await response.Content.ReadAsStringAsync();
        return JsonConvert.DeserializeObject<List<Schedule>>(stringData);
    }
    return null;

并修复方法调用

List<Schedule> list =  await GetScheduleList("https://localhost:7017/api/schedule");

或者你可以试试,如果你不使用异步

List<Schedule> list =  GetScheduleList("https://localhost:7017/api/schedule").Result;

【讨论】:

  • 问和回答了很多次。
  • @Serge,我想我今晚没有机会尝试修复,但我明天可能会有机会。如果有帮助,我会告诉你的。
【解决方案2】:

您是否尝试在调试模式下启动 Web 应用并找到 API 的返回? 您甚至可以使用 console.log 提供更多详细信息;

否则,我有一天会在那里。这是CORS问题。您应该添加标题:Access-Control-Allow-Origin 应该有通配符“*”作为值,以便能够在 http 服务器上调用 https API。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-11
    • 2014-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-14
    • 1970-01-01
    • 2015-10-04
    相关资源
    最近更新 更多