skip to Main Content

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

2

Answers


  1. 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());   
    }           
                    
    
    Login or Signup to reply.
  2. 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);
                }
        
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search