【问题标题】:Download asset from private GitHub repository release with Octokit.net使用 Octokit.net 从私有 GitHub 存储库发布下载资产
【发布时间】:2021-08-01 19:43:57
【问题描述】:

我正在尝试从我的私人 github 存储库下载最新资产,但每次我收到 404 错误时,这是​​我的代码:

// Initializes a GitHubClient
GitHubClient client = new GitHubClient(new ProductHeaderValue("MyClient"));
client.Credentials = new Credentials("my-token");

// Gets the latest release
Release latestRelease = client.Repository.Release.GetLatest("owner", "repo").Result;
string downloadUrl = latestRelease.Assets[0].BrowserDownloadUrl;

// Download with WebClient
using var webClient = new WebClient();
webClient.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36");
webClient.Headers.Add(HttpRequestHeader.Authorization, $"token {my-token}");

webClient.DownloadFileAsync(new Uri(downloadUrl), @"F:\Path\For\Storing\My\File.zip");
// this line creates the .zip file, but is always 0KB

我试过了-

  • 添加“Accept: application/octet-stream”标头;
  • 使用“用户名:密码”作为授权标头;
  • (坏主意,永远不要这样做!!!) 向令牌授予完整范围 他们都没有工作。

附:我知道 StackOverflow 上有无数类似的问题,但没有一个对我有用,而且我已经苦苦挣扎了好几个星期。

【问题讨论】:

    标签: c# github github-api octokit.net


    【解决方案1】:

    所以我终于想通了。您应该使用 GitHub REST Api 来下载文件,而不是直接链接。

    GET /repos/owner/repository/releases/assets/<asset_id>

    以下是更新后的代码:

    // Initializes a GitHubClient
    GitHubClient client = new GitHubClient(new ProductHeaderValue("MyClient"));
    client.Credentials = new Credentials("my-token");
    
    // Gets the latest release
    Release latestRelease = client.Repository.Release.GetLatest("owner", "repo").Result;
    int assetId = latestRelease.Assets[0].Id;
    string downloadUrl = $"https://api.github.com/repos/owner/repository/releases/assets/{assetId}";
    
    // Download with WebClient
    using var webClient = new WebClient();
    webClient.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36");
    webClient.Headers.Add(HttpRequestHeader.Authorization, "token my-token");
    webClient.Heasers.Add(HttpRequestHeader.Accept, "application/octet-stream");
    
    // Download the file
    webClient.DownloadFileAsync(downloadUrl, "C:/Path/To/File.zip");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-24
      • 1970-01-01
      • 2022-11-04
      • 2016-02-19
      • 1970-01-01
      • 2015-08-22
      • 1970-01-01
      • 2017-02-03
      相关资源
      最近更新 更多