System.Net.HttpStatusCode.Forbidden IsSuccessStatusCode = false

时间:2018-03-12 10:36:34

标签: asp.net asp.net-mvc rest asp.net-apicontroller

我试图访问https://api.github.com/users(api),我得到了这个。 {StatusCode:403,Version:1.0,Content:System.Net.Http.StreamContent,Headers:

RequestMessage = {Method:GET,RequestUri:'https://api.github.com/users',Version:1.1,Content :, Headers: {   接受:application / json }}

ReasonPhrase =“禁止” IsSuccessStatusCode = false

这是我的代码。

using Api_testing.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web.Mvc;

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

}

1 个答案:

答案 0 :(得分:1)

如果您检查实际的回复文本Res.Content.ReadAsStringAsync().Result,那么您会看到以下错误消息:

  

行政规则禁止请求。请确保您的请求具有User-Agent标头(http://developer.github.com/v3/#user-agent-required)。检查https://developer.github.com是否有其他可能的原因。

您需要添加User-Agent标头。

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

但更一般地说,您需要改进日志记录,以便了解事情不起作用的真正原因。