How to consume Github API on VS2019 avoiding 403 error on all requests?

Asked

Viewed 79 times

0

Somebody please save me. I need to consume the Github API for an internship challenge, but I’m caught in a 2-day problem, the challenge makes it clear that it’s not to use authentications, just use the open API. This below is the code I’m using that I got from Macoratti. The problem is that every time I try to access the URI inside VS2019 it returns 403 Forbidden, but if I access the same Uri by browsing it opens normal, by insominia same thing, I tested with another open API of any kind and I get the return 200 with Json with the same code below just replacing the parameter of the object Sponse.

Someone knows how to solve?


 static async Task Main()
        {
            // Create an HttpClientHandler object and set to use default credentials
            HttpClientHandler handler = new HttpClientHandler();
            handler.UseDefaultCredentials = true;
            
            // Create an HttpClient object
            HttpClient client = new HttpClient(handler);

            // Call asynchronous network methods in a try/catch block to handle exceptions
            try
            {
                
                HttpResponseMessage response = await client.GetAsync("https://api.github.com/");
                
                response.EnsureSuccessStatusCode();

                string responseBody = await response.Content.ReadAsStringAsync();
                Console.WriteLine(responseBody);
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine("\nException Caught!");
                Console.WriteLine("Message :{0} ", e.Message);
            }

            // Need to call dispose on the HttpClient and HttpClientHandler objects
            // when done using them, so the app doesn't leak resources
            handler.Dispose();
            client.Dispose();
        }
  • Try removing Try-catch and see what the exception tells you.

  • By the way, just see the HTTP response.

  • 1

    "Request Forbidden by administrative Rules. Please make sure your request has a User-Agent header (http://developer.github.com/v3/#user-agent-required). Check https://developer.github.com for other possible causes."

1 answer

1


You must specify a User agent in the header. Just adding the following code after booting your Httpclient should work

client.DefaultRequestHeaders.Add("User-Agent", "request");

Browser other questions tagged

You are not signed in. Login or sign up in order to post.