0

tl;dr: I have an API that works in the browser, but I can't figure out how to return a list of items so I can traverse them in a List.

Long version: I'm still struggling with API's and now I've hit another snag. I have the following code in my 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);
        }
    }

When I navigate to my localhost (https://localhost:7017/api/schedule) it returns the data just fine:

[{"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"}
...]

So far, so good. Now, I want to return the list to the client calling the API. I've made a simple test client that should get the list when I press a button:

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...

However, I can't figure out how this method should work:

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

Every tutorial I can find online, says to use GetAsync. However, that only works with the await keyword. Adding the await keyword means I have to add the async keyword to my method, which means I must return a Task<List> or a task-like type, which can't be converted to a List. If I return it as a Task, how can I then break it back down into my list of schedules?

I really feel like I've tried anything I've come across, so any help you can give is much appreciated.

VLAZ
  • 26,331
  • 9
  • 49
  • 67
starspejd
  • 13
  • 1
  • 4
  • you need to json deserialize – pm100 Feb 22 '22 at 21:05
  • your GetScheduleList needs to be async, since you need await in client.GetAsync. Also you need to call your service to get schedules, currently it returns null – Nonik Feb 22 '22 at 21:07
  • If you're using .NET Core, please use `IHttpClientFactory`. See [Use IHttpClientFactory to implement resilient HTTP requests](https://learn.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests) – Heretic Monkey Feb 22 '22 at 21:08

2 Answers2

0

try this

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;

and fix the method call

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

or you can try, if you don't use async

List<Schedule> list =  GetScheduleList("https://localhost:7017/api/schedule").Result;
Serge
  • 40,935
  • 4
  • 18
  • 45
  • @Serge, I don't think I'll get the chance to try the fix tonight, but I might get a chance tomorrow. I'll let you know if it helps. – starspejd Feb 23 '22 at 17:04
0

did you try to start the web app in debug mode and find the return of the API ? You can even use console.log to give more details;

Otherwise, I was there one day. it's CORS problem. you should add the header : Access-Control-Allow-Origin should have wildcard "*" as a value in order to be able to call https APIs on http servers.