public async Task <List <VehicleModel> > GetAllVehiclesAsync() { StringBuilder url = new StringBuilder(); //base address https://swapi.co/api/ url.Append(ApiHelper.ApiClient.BaseAddress.ToString()); url.Append("vehicles"); using (HttpResponseMessage response = await ApiHelper.ApiClient.GetAsync(url.ToString())) { if (response.IsSuccessStatusCode) { List <VehicleModel> vehicles = new List <VehicleModel>(); //get first page of planets string responseString = await response.Content.ReadAsStringAsync(); JObject results = JsonConvert.DeserializeObject <JObject>(responseString); vehicles.AddRange( results.Value <JArray>("results") .ToObject <List <VehicleModel> >()); string next = results.GetValue("next").Value <string>(); //fetch the rest of the planet pages while (!string.IsNullOrWhiteSpace(next) && next != "null") { VehicleResponseModel vehicleResponse = await GetVehiclePageAsync(next); next = vehicleResponse.ResponseNext; vehicles.AddRange(vehicleResponse.vehicles); } return(vehicles); } else { throw new Exception(response.ReasonPhrase); } } }
//SS 27/3 Get method to request all vehicle details from the database public string Get() { //Create a response object which will hold a list of vehicles, list of fuel types and any error messages VehicleResponseModel vrm = new VehicleResponseModel(); try { //Get all vehicle data List <VehicleMake> vehicleMakes = _context.VehicleMake .Include(vm => vm.VehicleModel) .ThenInclude(vm => vm.Vehicle) .ToList(); //Get all fuel type data List <FuelTypeModel> fuelTypes = _context.FuelType .Select(ft => new FuelTypeModel { FuelTypeId = ft.FuelTypeId, FuelTypeName = ft.Name }) .ToList(); //Assemble response vrm.VehicleMakes = vehicleMakes; vrm.FuelTypes = fuelTypes; vrm.Success = true; } catch (Exception e) { //If an exception was thrown, add the error message vrm.Success = false; vrm.ErrorMessage = e.Message; } return(JsonConvert.SerializeObject(vrm, Formatting.Indented, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore })); }
public async Task <VehicleResponseModel> GetVehiclePageAsync(string url) { using (HttpResponseMessage response = await ApiHelper.ApiClient.GetAsync(url.ToString())) { if (response.IsSuccessStatusCode) { VehicleResponseModel vehicleResponse = new VehicleResponseModel(); string responseString = await response.Content.ReadAsStringAsync(); JObject results = JsonConvert.DeserializeObject <JObject>(responseString); vehicleResponse.vehicles.AddRange( results.Value <JArray>("results") .ToObject <List <VehicleModel> >()); vehicleResponse.ResponseNext = results.GetValue("next").Value <string>(); return(vehicleResponse); } else { throw new Exception(response.ReasonPhrase); } } }