【问题标题】:Access a file from Private GitHub Repository from C#从 C# 访问私有 GitHub 存储库中的文件
【发布时间】:2019-09-27 15:32:50
【问题描述】:

以下是我如何从控制台应用程序访问公共 GitHub 存储库中的单个文件的示例。我可以为私有存储库做同样的事情吗?我不确定如何更改代码,或者是否需要使用不同的授权设置访问它。

谁能告诉我我做错了什么?

我不确定这是否会帮助https://developer.github.com/v3/guides/managing-deploy-keys/

    private static void Main(string[] args)
    {
        var file = $"https://raw.githubusercontent.com/{username}/{repositoryName}/{branch}/{filePath}";

        System.IO.File.WriteAllText($"c:\\{filePath}", GetFile(file));

        System.Console.ReadKey();
    }

    public static string GetFile(string input)
    {
        var output = string.Empty;
        HttpWebRequest request = (HttpWebRequest)System.Net.WebRequest.Create(input);

        request.Headers.Add("Authorization", githubtoken);
        request.AllowAutoRedirect = true;

        var response = (HttpWebResponse)request.GetResponse();

        using (var stream = new System.IO.MemoryStream())
        {
            response.GetResponseStream().CopyTo(stream);
            output = System.Text.Encoding.ASCII.GetString(stream.ToArray());
        }

        response.Close();

        return output;
    }

编辑:

因此,根据反馈(感谢 Olivier),我使用的任何 githubtoken 的使用似乎都会返回 403 或 404。我的令牌已读取:packages & read:repo_hook,我认为这就足够了。我使用以下link 向我展示了如何创建令牌。我是否需要其他任何东西才能使用令牌访问私人仓库?

我可以通过用户名和密码访问此文件吗?如果可以,如何更改上述内容以获取文件?

【问题讨论】:

标签: c# .net github-api


【解决方案1】:

我之前在尝试访问文件时拥有read:packagesread:repo_hook 权限,但缺少repo 权限。一旦提供并重新运行上述内容,它就开始工作了

我还必须将我的网址更改为https://api.github.com/repositories/{repositoryId}/contents/{filePath} 并且在尝试获得响应之前必须将request.UserAgent = githubUsername; 添加到请求中

感谢Olivier Rogier给了我线索

【讨论】:

    【解决方案2】:

    将授权标头更改为:

    request.Headers.Add("Authorization", "token " + githubtoken);
    
    

    【讨论】:

      猜你喜欢
      • 2018-11-27
      • 2013-03-23
      • 2023-03-16
      • 2018-11-02
      • 2013-08-17
      • 2018-09-23
      • 1970-01-01
      • 1970-01-01
      • 2021-01-18
      相关资源
      最近更新 更多