0

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:

enter image description here

1 Answer 1

0

Make sure your API-key is correct. I tried it and it worked for me. You can test your URL string by doing this:

[HttpGet("UrlTest")]
public async Task<IActionResult> GetUrl()
{

    var apiKey = "top-headlines?country=us&apiKey=" + _configuration.GetValue<string>("Keys:NewsAPI");
        var url = "https://newsapi.org/v2/";

    return UltimateResourceFallbackLocation + apiKey;
}

This will give you your URL. Then simply paste it into your browser and you should get a value back.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.