HttpClient GetAsync 方法 403 错误

HttpClient GetAsync Method 403 error

我正在尝试 github 存储库的简单显示。 url“https://api.github.com/search/repositories?q=pluralsight”在我的浏览器 return json 中工作,在 fiddler 中工作,但我的 .NET Web 应用程序中的以下内容出现 403 Forbidden 错误。任何人都可以帮助我了解修复方法吗?我的控制器如下:

public class HomeController : Controller
    {
    public ActionResult Index()
        {
        Tweets model = null;
        var client = new HttpClient();
        var task = client.GetAsync("https://api.github.com/search/repositories?q=pluralsight")
            .ContinueWith((taskwithresponse) =>
            {
                var response = taskwithresponse.Result;
                response.EnsureSuccessStatusCode();
                var readtask = response.Content.ReadAsAsync<Tweets>();
                readtask.Wait();
                model = readtask.Result;

            });
        task.Wait();
        return View(model.results);
        }
    }

我有一个class定义如下(忽略它被称为Tweets)最初是试图访问twitter api。

namespace HttpClientMVCDemo.Controllers
{
public class Tweets
    {
    public Tweet[] results;
    }
public class Tweet
    {
    [JsonProperty("name")]
    public string UserName { get; set; }
    [JsonProperty("id")]
    public string id { get; set; }
    }
}

根据以下 Amit 的 classes 自动生成的代码视图:

@model IEnumerable<HttpClientMVCDemo.Controllers.Gits>

@{
ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
    <th>
        @Html.DisplayNameFor(model => model.total_count)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.incomplete_results)
    </th>
    <th></th>
</tr>

@foreach (var item in Model) {
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.total_count)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.incomplete_results)
    </td>
    <td>
        @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
        @Html.ActionLink("Details", "Details", new       { /*id=item.PrimaryKey*/ }) |
        @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
    </td>
</tr>
}

好吧,这里是您模型中的一些修改 class

第一个 Json 字符串包含 项数组 而不是 结果

并且您忘记在模型中提供 get 和 set 属性 class。

所以这是新修改的模型 class。

public class Tweets
    {
        public int total_count { get; set; }
        public bool incomplete_results { get; set; }
        public List<Item> items { get; set; }
    }

    public class Item
    {
        public int id { get; set; }
        public string name { get; set; }
        public string full_name { get; set; }
    }

要从 url 获取数据,您需要在请求中添加 User-Agent header。 并将其添加到您的 web.cofig 文件

<system.net>
    <settings>
      <httpWebRequest useUnsafeHeaderParsing="true" />
    </settings>
  </system.net>

这是完整的代码。

Tweets model = null;           
            var client = new HttpClient();
            client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "http://developer.github.com/v3/#user-agent-required");
            var task = client.GetAsync("https://api.github.com/search/repositories?q=pluralsight")
                .ContinueWith((taskwithresponse) =>
                {
                    var response = taskwithresponse.Result.Content.ReadAsStringAsync();
                    response.Wait();
                    model = JsonConvert.DeserializeObject<Tweets>(response.Result);
                });
            task.Wait();
            return View(model.items);

而且在你看来应该接受这种模式

@model IEnumerable<HttpClientMVCDemo.Controllers.Item>

您的浏览器会自动向请求添加几个接受 headers。您可能需要在请求中添加 headers 以避免 403.

 httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "text/html,application/json");

类似的问题是here。最简单的方法是使用 Fiddler 来检查您的请求。

此外,您不应在异步调用中调用 Wait。最好将操作声明为 async 并调用 await client.GetAsync(); 否则你可能会遇到死锁。参见 here

HTTP 403:由于来自 github 网站的管理规则而被禁止。

从 github 站点访问 api(https://api.github.com/) 需要 'User-Agent' header.

这可以使用以下代码解决:

HttpClient Client = new HttpClient();    
Client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "http://developer.github.com/v3/#user-agent-required");
var res = Client.GetAsync("https://api.github.com/search/repositories?q=pluralsight").Result.Content.ReadAsStringAsync().Result;

参考: https://docs.github.com/en/free-pro-team@latest/rest/overview/resources-in-the-rest-api#user-agent-required