I am new to ASP.NET Core Web API and I'm trying to learn how to return a call from a News API (https://newsapi.org/). But I keep getting a 400 status code and cannot figure out what is wrong with my code so far.
[ApiController]
[Route("[controller]")]
public class NewsController : Controller
{
private readonly IConfiguration _configuration;
public NewsController(IConfiguration iconfig)
{
_configuration = iconfig;
}
[HttpGet]
public async Task<IActionResult> GetNews()
{
var apiKey = "top-headlines?country=us&apiKey=" + _configuration.GetValue<string>("Keys:NewsAPI");
var url = "https://newsapi.org/v2/";
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync(apiKey);
if (!response.IsSuccessStatusCode)
{
return StatusCode((int)response.StatusCode);
}
return Ok(response.Content);
}
}
I made sure my URL is correct and that it works while debugging HttpResponseMessage. And followed instructions from Asp.Net Core - Making API calls from backend and Microsoft docs but I'm lost here.
This is the response body I'm getting:
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "Bad Request",
"status": 400,
"traceId": "00-fceadd8306e1d45106d330bb98529ae0-9c6374c80d070b7a-00"
}
Debugger:
