不幸的是,在以下情况下,我陷入了困境:
我正在使用.NET Core 3.1,并使用HttpClient(类型化客户端)通过DI从URL中获取数据。此数据是一个csv文件,应上传到Azure Blob存储。在这一点上,我试图将其上传到Blob存储,但似乎失败,但出现以下异常:
System.Net.Http: The operation was canceled. System.Net.Http: Error while copying content to a stream.
System.Net.Sockets: Unable to read data from the transport connection: The I/O operation has been aborted because of either a thread exit or an application request..
The I/O operation has been aborted because of either a thread exit or an application request.
我目前不知道为什么上传失败。来自其他流的其他上传似乎可以正常运行。你们中有人有我的头绪吗?
我的课程
public class Web<T> where T : BlobStorageContext
{
private HttpClient _client { get; }
private ILogger<Web> _logger;
private Csv<T> _csv { get; }
public Web(HttpClient client, Csv<T> csv, ILogger<Web> logger)
{
_client = client;
_logger = logger;
_csv = csv;
}
public async Task AccessWebFileAndSaveToAzureAsync()
{
...
var request = new HttpRequestMessage(HttpMethod.Get,
url);
using (var response = await _client.SendAsync(request))
{
await using (var str = await response.Content.ReadAsStreamAsync())
{
await _csv.WriteFileToAzureAsync(str);
}
}
}
}
public class Csv<T> where T : BlobStorageContext
{
private BlobServiceClient _blobServiceClient { get; set; }
private ILogger<Csv<T>> _logger { get; set; }
public Csv(IOptions<BlobStorageConfiguration<T>> configuration, ILogger<Csv<T>> logger)
{
_blobServiceClient = new BlobServiceClient(configuration.Value.ConnectionString());
_logger = logger;
}
public async Task WriteFileToAzureAsync(Stream str)
{
var container = _blobServiceClient.GetBlobContainerClient("container);
var blob = container.GetBlobClient(blobPath);
await blob.UploadAsync(str, true);
}
}
答案 0 :(得分:-1)
复制连接字符串并在upload_ToBlob()方法中分配给storageAccount_connectionString变量
storageAccount_connectionString = "your Azure storage account connection string"
以下语句用于为存储帐户,Blob客户端和Blob容器创建对象。
CloudStorageAccount mycloudStorageAccount = CloudStorageAccount.Parse(storageAccount_connectionString);
CloudBlobClient blobClient = mycloudStorageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference(azure_ContainerName);
此代码用于检查存储帐户中是否存在指定的容器。
如果存在,则应用程序将使用现有容器。否则,它将在具有指定名称的存储帐户内创建一个容器。
if (container.CreateIfNotExists())
{
container.SetPermissionsAsync(new
BlobContainerPermissions
{
PublicAccess =BlobContainerPublicAccessType.Blob
});
}
以下语句用于使用带有扩展名的文件名创建一个Block blob对象
CloudBlockBlob cloudBlockBlob = container.GetBlockBlobReference(filename_withExtension);
cloudBlockBlob.UploadFromStreamAsync(file)语句用于将文件上传到Blob存储。