Daniel Stephen
Daniel Stephen

Reputation: 579

Unable to consume the web API with header using API KEY dot net

I am unable to consume the weather API. I am getting this message "Unathorized or not getting the response". I am not getting the http response. Please help me to get the response. When I try the URL and headers in post man i am getting the below output. Please help me on this. I think my correct is incorrect.

Code in console application dot net Visual 2022:

using Microsoft.AspNetCore.Http;

HttpClient client = new HttpClient();
var responsetask = client.GetAsync("https://weatherapi-com.p.rapidapi.com/ip.json?q=100.0.0.1");

responsetask.Wait();

if (responsetask.IsCompleted)
{
    var result = responsetask.Result;
    result.Headers.Add("X-RapidAPI-Host", "weatherapi-com.p.rapidapi.com");
    result.Headers.Add("X-RapidAPI-Key", "API KEY");
    
    if (result.IsSuccessStatusCode)
    {
        var messagetask = result.Content.ReadAsStringAsync();
        Console.WriteLine(messagetask.Result);
        Console.ReadLine();
    }

    Console.WriteLine(result);
    Console.ReadLine();
}

Excepted output:

{
    "ip": "100.0.0.1",
    "type": "ipv4",
    "continent_code": "NA",
    "continent_name": "North America",
    "country_code": "US",
    "country_name": "United States",
    "is_eu": "false",
    "geoname_id": 4952762,
    "city": "Tewksbury",
    "region": "Massachusetts",
    "lat": 42.6028,
    "lon": -71.2319,
    "tz_id": "America/New_York",
    "localtime_epoch": 1653060449,
    "localtime": "2022-05-20 11:27"
}

Upvotes: 0

Views: 469

Answers (1)

SlobodanT
SlobodanT

Reputation: 431

I think you should be adding your auth key to the header before executing the http request, and not after you get the result.

Upvotes: 1

Related Questions