0

我正在尝试从我的私人 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

我试过了 -

  • 添加“接受:应用程序/八位字节流”标头;
  • 使用“用户名:密码”作为授权标头;
  • (坏主意,永远不要这样做!!!)向令牌授予完整范围,但它们都不起作用。

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

4

1 回答 1

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");
于 2021-05-11T13:51:57.430 回答