c# - 使用 URI 中的 api_key 查询字符串将公共(public)镜像复制到 Azure 存储

标签 c# azure azure-blob-storage

我使用 C# Azure 存储客户端获取图像,然后复制到 Azure 存储 blob 容器,格式如下:

https://some-image-server.com/2023/03/13.png?api_key=my-api-key

我正在使用 StartCopyFromUriAsync,如下所示:

await blobClient.StartCopyFromUriAsync(new Uri(imageUrl));

我的代码可以很好地处理没有 api_key 查询字符串的常规公共(public)图像。但使用上述图像格式时,客户端将 0 KB 复制到 Azure 存储,并且 Copy StatusFailed(响应 header 指出一般 500 错误)。由于该图像并未真正公开,因此这是不行的吗?我是否必须使用流或其他替代方案?

最佳答案

The issue you are getting from the StartCopyFromUriAsync method does not support copying images that require authentication.

该图像需要一个 api_key 查询字符串才能访问,该字符串不是公开的。

要将图像复制到 Azure 存储,您需要使用 HTTP 客户端 下载图像,该客户端可以使用 api_key 查询字符串对请求进行身份验证。

下载镜像后,需要使用BlobClientUploadAsync方法将其上传到Azure存储

有关更多信息,请查看 Github Issue #32684

HttpClient http_Client = new HttpClient();
http_Client.DefaultRequestHeaders.Add("api_key", apiKey);

HttpResponseMessage resp = await http_Client.GetAsync(imageUrl);
resp.EnsureSuccessStatusCode();
Stream contentStream = await resp.Content.ReadAsStreamAsync();
BlobServiceClient blobService_Client = new BlobServiceClient(conn_String);
BlobContainerClient container_Client = blobServiceClient.GetBlobContainerClient(container);
BlobClient blob_Client = containerClient.GetBlobClient(blob);

await blobClient.UploadAsync(contentStream, true);

将一个存储复制到另一个存储的示例。

使用 StartCopyFromUriAsync 方法,通过 URI 中的 api_key 查询字符串将公共(public)镜像复制到 Azure 存储

BlobServiceClient srcBlobServiceClient = new BlobServiceClient(srcConnectionString);
BlobServiceClient destBlobServiceClient = new BlobServiceClient(destConnectionString);

BlobContainerClient srcContainerClient = srcBlobServiceClient.GetBlobContainerClient(srcContainerName);
BlobContainerClient destContainerClient = destBlobServiceClient.GetBlobContainerClient(destContainerName);

BlobClient srcBlobClient = srcContainerClient.GetBlobClient(srcBlobName);
BlobClient destBlobClient = destContainerClient.GetBlobClient(destBlobName);

await destBlobClient.StartCopyFromUriAsync(srcBlobClient.Uri);

enter image description here

在 azure

enter image description here

有关更多信息,请查看此 Blog.

关于c# - 使用 URI 中的 api_key 查询字符串将公共(public)镜像复制到 Azure 存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76011431/

相关文章:

c# - 作为流访问 TextReader

javascript - Telerik过滤功能

c# - 如何在应用程序启动时最大化 WPF 页面?

c# - ASP.NET 中的 P/Invoke(Dll 未找到异常)

c# - 如何在 C# 中检索 azure 安全组

python - 将多个 blob 输入到 azure 函数 python 中

javascript - Angular 6 TypeScript 中的 Azure Blob 元数据

c# - 访问 IOption 类中 appsettings.json 文件中存储的键值对

不正常退出后 Azure Blob 租约不会释放?

c# - Azure Blob 存储 DownloadTextAsync 与 BlobRequestOptions