我正试图从我的私人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:PathForStoringMyFile.zip");
// this line creates the .zip file, but is always 0KB
我试过了-
- 添加";接受:应用程序/八位字节流";表头
- 使用";用户名:密码";作为授权头
- (坏主意,千万不要这样做!!(授予令牌完整作用域他们都不起作用
p.S.我知道StackOverflow上有无数类似的问题,但没有一个对我有效,我已经挣扎了好几个星期。
所以我终于想通了。您应该使用GitHubRESTApi下载该文件,而不是直接链接。
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.Headers.Add(HttpRequestHeader.Accept, "application/octet-stream");
// Download the file
webClient.DownloadFileAsync(downloadUrl, "C:/Path/To/File.zip");