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);
}
}
}
}