REST API未从AZURE git分支下载文件

64jmpszr  于 2023-01-14  发布在  Git
关注(0)|答案(1)|浏览(86)

我是C#新手,尝试从Azure Git repo下载一个文件。响应状态是成功,但没有将文件下载到本地驱动器。我正确地传递了所有参数。

using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(
    new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
    Convert.ToBase64String(
    System.Text.ASCIIEncoding.ASCII.GetBytes(
    string.Format("{0}:{1}", "", personalaccesstoken))));

    using (HttpResponseMessage response = client.GetAsync(
        $"https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repositoryId}/items?path={path}&download={download}&versionDescriptor.versionType={versionDescriptor_versionType}&versionDescriptor.version={versionDescriptor_version}&api-version=7.0").Result)
        {
            response.EnsureSuccessStatusCode();
             var responseBody = await response.Content.ReadAsStringAsync();

            Console.WriteLine(responseBody);

        }
}

我得到的输出如下。

{
  "objectId": "34e9cd84219e51533b19b3a70121e73b612c0eca",
  "gitObjectType": "blob",
  "commitId": "1916fd237ce345505a0cdbb285ce0ba71a64691b",
  "path": "/Backend/DATA/Document_AA083_A100001.xml",
  "url": "https://dev.azure.com/xxxx-xxx-xxx/00e7c28c-efde-450e-91a1-133b7f2a228c/_apis/git/repositories/062ef079-ab27-4ed9-ba91-aaa0678d89b5/items?path=%2FBackend%2FDATA%2FDocument_AA083_A100001.xml&versionType=Branch&version=tcs00107%2FGIT_Tool&versionOptions=None",
  "_links": {
    "self": {
      "href": "https://dev.azure.com/xxxx-xxx-xxx/00e7c28c-efde-450e-91a1-133b7f2a228c/_apis/git/repositories/062ef079-ab27-4ed9-ba91-aaa0678d89b5/items?path=%2FBackend%2FDATA%2FDocument_AA083_A100001.xml&versionType=Branch&version=tcs00107%2FGIT_Tool&versionOptions=None"
    },
    "repository": {
      "href": "https://dev.azure.com/xxxx-xxx-xxx/00e7c28c-efde-450e-91a1-133b7f2a228c/_apis/git/repositories/062ef079-ab27-4ed9-ba91-aaa0678d89b5"
    },
    "blob": {
      "href": "https://dev.azure.com/xxxx-xxx-xxx/00e7c28c-efde-450e-91a1-133b7f2a228c/_apis/git/repositories/062ef079-ab27-4ed9-ba91-aaa0678d89b5/blobs/34e9cd84219e51533b19b3a70121e73b612c0eca"
    }
  }
}

如果有人能帮我解决这个问题,那将是非常有帮助的。非常感谢你的帮助。

zrfyljdw

zrfyljdw1#

问题是你得到的JSON响应包含了关于文件的元数据。你必须使用“url”并使用“HttpClient.GetByteArrayAsync()"执行另一个get请求。这会得到一个字节数组形式的文件,然后可以使用“File.WriteAllBytes(string,byte[])"将其写入本地驱动器。

using (HttpClient client = new HttpClient())
{
    //.. your existing code 
    var responseBody = await response.Content.ReadAsStringAsync();
    dynamic jsonData = JsonConvert.DeserializeObject(responseBody);
    var blobUrl = jsonData._links.blob.href;
    byte[] fileBytes = await client.GetByteArrayAsync(blobUrl);
    File.WriteAllBytes("path/to/local/file", fileBytes);
}

将路径更改为要保存文件的位置,并注意对文件路径的任何权限/限制。

相关问题