I am trying to fetch the holiday data from an external API in asp.net. The fetch works, but I'd like to use it as a reference on the annual date.
cspublic string Get()
{
HttpClient http = new HttpClient();
http.DefaultRequestHeaders.Add("APIKey", "Application/Json");
var data = http.GetAsync(url).Result.Content.ReadAsStringAsync().Result;
return data;
}
i have this code in my repository file to get external api
i want to get is_national_holiday == true
https://api-harilibur.vercel.app/api
[
{
"holiday_date": "2021-01-1",
"holiday_name": "Tahun Baru Masehi",
"is_national_holiday": true
},
{
"holiday_date": "2021-01-12",
"holiday_name": "Hari Siwa Ratri",
"is_national_holiday": false
},
{
"holiday_date": "2021-01-30",
"holiday_name": "Hari Saraswati",
"is_national_holiday": false
},
{
"holiday_date": "2021-02-12",
"holiday_name": "Tahun Baru Imlek 2572 Kongzili",
"is_national_holiday": true
}
]
Update :
Repository
public async Task<HoliDate> GetHolidaysAsync()
{
var client = new RestClient($"https://api-harilibur.vercel.app/api");
var request = new RestRequest(Method.GET);
IRestResponse response = await client.ExecuteAsync(request);
if (response.IsSuccessful)
{
var content = JsonConvert.DeserializeObject<JToken>(response.Content);
var holidayCaption = content["holiday_date"].Value<DateTime>();
var holidays = content.SelectTokens("aa")
.Select(team => new Holiday
{
holiday_date = (DateTime)team["holiday_date"],
holiday_name = (string)team["holiday_name"],
is_national_holiday = (bool)team["is_national_holiday"]
})
.ToList();
//return the model to my caller.
return new HoliDate
{
HolidayCaption = holidayCaption,
Holiday = holidays
};
}
Console.WriteLine(response.Content);
return null;
}
Controller
[Route("Holiday")]
[HttpGet]
public async Task<IActionResult> GetByIdAsync() {
var model = await repository.GetHolidaysAsync();
if (model == null)
return NotFound();
return Ok(model);
}
Model Holiday
public class HoliDate
{
public DateTime HolidayCaption { get; set; }
public IEnumerable<Holiday> Holiday { get; set; }
}
}
An unhandled exception occurred while processing the request. ArgumentException: Accessed JArray values with invalid key value: "HolidayCaption". Int32 array index expected. Newtonsoft.Json.Linq.JArray.get_Item(object key) LeaveAPI.Repository.Data.LeaveDetailRepository.GetHolidaysAsync() in LeaveDetailRepository.cs + var holidayCaption = content["HolidayCaption"].Value(); LeaveAPI.Controllers.LeaveDetailsController.GetByIdAsync() in LeaveDetailsController.cs + var model = await repository.GetHolidaysAsync();