Search code examples
asp.netasp.net-mvcrestasp.net-apicontroller

Requesting https://api.github.com/users (api) returns System.Net.HttpStatusCode.Forbidden IsSuccessStatusCode = false


I tried to do an api request to https://api.github.com/users and I got this forbidden response returned. As it doesn't need authentication, I don't know why I got that 403 returned.

{StatusCode: 403, Version: 1.0, Content: System.Net.Http.StreamContent, 
Headers:

RequestMessage = {Method: GET, RequestUri: 'https://api.github.com/users', 
Version: 1.1, Content: <null>, Headers:
{
   Accept: application/json
}}

ReasonPhrase = "Forbidden"
IsSuccessStatusCode = false

This following is my code.

namespace ConsumingWebAapiRESTinMVC.Controllers
{
public class HomeController : Controller
    {
    //Hosted web API REST Service base url  
    string Baseurl = "https://api.github.com/users";
    public async Task<ActionResult> Index()
    {
        List<Employee> EmpInfo = new List<Employee>();

        using (var client = new HttpClient())
        {
            //Passing service base url  
            client.BaseAddress = new Uri(Baseurl);

            client.DefaultRequestHeaders.Clear();
            //Define request data format  
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            //Sending request to find web api REST service resource GetAllEmployees using HttpClient  
            HttpResponseMessage Res = await client.GetAsync(Baseurl);

            //Checking the response is successful or not which is sent using HttpClient  
            if (Res.IsSuccessStatusCode)
            {
                //Storing the response details recieved from web api   
                var EmpResponse = Res.Content.ReadAsStringAsync().Result;

                //Deserializing the response recieved from web api and storing into the Employee list  
                EmpInfo = JsonConvert.DeserializeObject<List<Employee>>(EmpResponse);

            }
            //returning the employee list to view  
            return View(EmpInfo);
        }
    }
}

}


Solution

  • If you check the actual response text Res.Content.ReadAsStringAsync().Result then you would have seen the following error message:

    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.

    You need to add a User-Agent header.

    client.DefaultRequestHeaders.Add("User-Agent", "C# App");
    

    But more generally, you need to improve your logging so that you are seeing the real reasons things aren't working.