I created a web API application for public holidays.
Here is the class Pho
public class Pho
{
public DateTime date { get; set; }
public string localName { get; set; }
public string countryCode { get; set; }
}
Here the code I tried to call the API
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://date.nager.at/api/v3/PublicHolidays/2017/FR");
using (HttpResponseMessage response = await client.GetAsync(""))
{
var responseContent = response.Content.ReadAsStringAsync().Result;
response.EnsureSuccessStatusCode();
return Ok(responseContent);
}
}
It didn't work and I didn't know how to fix it
CodePudding user response:
try to fix uri
client.BaseAddress = new Uri("https://date.nager.at");
using (HttpResponseMessage response = await client.GetAsync("/api/v3/PublicHolidays/2017/FR"))
{
if (response.IsSuccessStatusCode)
{
var responseContent = await response.Content.ReadAsStringAsync();
return Ok(responseContent);
}
return BadRequest("status code " response.StatusCode.ToString());
}
CodePudding user response:
One of the possible reasons your code is not working is because you're trying to set BaseAddress when the client hasn't been initialized yet.
To add BaseAddress at the time of intializing HttpClient you should do it this way:
var client = new HttpClient
{
BaseAddress = new Uri("https://date.nager.at/api/v3/PublicHolidays/2017/FR")
};
using (HttpResponseMessage response = await client.GetAsync(client.BaseAddress))
{
var responseContent = response.Content.ReadAsStringAsync().Result;
response.EnsureSuccessStatusCode();
return Ok(responseContent);
}