You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用C# REST API获取GitHub用户数据遇404错误求助

Hey there! Let's figure out why you're hitting that 404 error when fetching GitHub user data. Here are the key issues and fixes to get your code working:

1. First, Verify the Username Exists

The most common cause of a 404 with the GitHub API is that the target username doesn't exist. If testUser was just a placeholder, swap it for a real, existing username (like octocat) and test again—this alone might fix your issue.

2. Add Error Handling & Refine Request Headers

Your current code lacks error catching, which makes it hard to debug exactly what's going wrong. Plus, while you set the required UserAgent header (GitHub mandates this), we can add a few more headers for stability and handle non-success responses properly.

Here's an updated version of your code with these fixes:

private void GetGithubData()
{
    string username = "octocat"; // Replace with a valid GitHub username
    var url = $"https://api.github.com/users/{username}/repos?page=1&per_page=100"; // Add per_page to fetch more repos per request

    try
    {
        HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
        request.Method = "GET";
        request.ContentType = "application/json";
        request.UserAgent = "TestApp"; // Required by GitHub API
        request.Accept = "application/vnd.github.v3+json"; // Specify API version for consistency

        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
        {
            if (response.StatusCode == HttpStatusCode.OK)
            {
                using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                {
                    string jsonResponse = reader.ReadToEnd();
                    // Here you can parse the JSON (e.g., with Newtonsoft.Json or System.Text.Json)
                    Console.WriteLine(jsonResponse);
                }
            }
            else
            {
                Console.WriteLine($"API returned error status: {response.StatusCode}");
            }
        }
    }
    catch (WebException ex)
    {
        // Catch and log detailed error info
        using (HttpWebResponse errorResponse = ex.Response as HttpWebResponse)
        {
            if (errorResponse != null)
            {
                Console.WriteLine($"Request failed with status: {errorResponse.StatusCode}");
                using (StreamReader reader = new StreamReader(errorResponse.GetResponseStream()))
                {
                    string errorDetails = reader.ReadToEnd();
                    Console.WriteLine("Error details: " + errorDetails);
                }
            }
        }
    }
}
3. Handle Pagination for Full Repository Data

GitHub's API returns 30 repos per page by default. To get all a user's repositories, you'll need to loop through pages until you get an empty response. Here's how to extend your code for that:

private void GetAllGithubRepos(string username)
{
    int page = 1;
    List<string> allRepoNames = new List<string>();

    while (true)
    {
        var url = $"https://api.github.com/users/{username}/repos?page={page}&per_page=100";
        try
        {
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = "GET";
            request.UserAgent = "TestApp";
            request.Accept = "application/vnd.github.v3+json";

            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                {
                    string json = reader.ReadToEnd();
                    // Deserialize JSON (requires Newtonsoft.Json NuGet package)
                    var repos = Newtonsoft.Json.JsonConvert.DeserializeObject<List<dynamic>>(json);
                    
                    if (repos.Count == 0)
                        break; // No more repos to fetch

                    allRepoNames.AddRange(repos.Select(repo => repo.name.ToString()));
                    page++;
                }
            }
        }
        catch (WebException ex)
        {
            Console.WriteLine($"Pagination request failed: {ex.Message}");
            break;
        }
    }

    Console.WriteLine($"Successfully fetched {allRepoNames.Count} repositories");
}
4. Consider Using HttpClient Instead of HttpWebRequest

HttpWebRequest is an older API—for cleaner, more modern code (especially with async/await), use HttpClient (available in .NET Framework 4.5+):

private async Task GetGithubDataWithHttpClient()
{
    string username = "octocat";
    var url = $"https://api.github.com/users/{username}/repos?page=1&per_page=100";

    using (HttpClient client = new HttpClient())
    {
        client.DefaultRequestHeaders.UserAgent.ParseAdd("TestApp");
        client.DefaultRequestHeaders.Accept.ParseAdd("application/vnd.github.v3+json");

        try
        {
            HttpResponseMessage response = await client.GetAsync(url);
            if (response.IsSuccessStatusCode)
            {
                string jsonResponse = await response.Content.ReadAsStringAsync();
                Console.WriteLine(jsonResponse);
            }
            else
            {
                string errorDetails = await response.Content.ReadAsStringAsync();
                Console.WriteLine($"Request failed: {response.StatusCode}\nDetails: {errorDetails}");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Request error: {ex.Message}");
        }
    }
}

内容的提问来源于stack exchange,提问作者Crisly Domingos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 21:42:45