【发布时间】:2021-03-31 16:35:47
【问题描述】:
我将附件上传到 Azure Blob 存储。上传时我还创建了一个 SAS-Token;我检索唯一 URL,将其发送到立即打开的浏览器。
当我这样做时,我经常(但不总是)检索到此资源不存在的 404。几秒钟后刷新页面时,它会被正确检索。
所以上传附件后我似乎“太快了”。有没有办法等到 Azure 准备好提供附件?我原以为等待电话就足以实现这一目标。
public async void UploadFile(string filename, byte[] filecontent)
{
var containerClient = _blobServiceclient.GetBlobContainerClient("attachments");
var blobClient = containerClient.GetBlobClient(filename);
using (var stream = new MemoryStream(filecontent))
{
await blobClient.UploadAsync(stream, new BlobHttpHeaders { ContentType = GetContentTypeByFilename(filename) });
}
}
public async Task<string> GetLinkForFile(string filename)
{
var containerClient = _blobServiceclient.GetBlobContainerClient("attachments");
var sasBuilder = new BlobSasBuilder()
{
BlobContainerName = containerName,
BlobName = filename,
Resource = "b",
StartsOn = DateTime.UtcNow.AddMinutes(-1),
ExpiresOn = DateTime.UtcNow.AddMinutes(5),
};
// Specify read permissions
sasBuilder.SetPermissions(BlobSasPermissions.Read);
var credentials = new StorageSharedKeyCredential(_blobServiceclient.AccountName, _accountKey);
var sasToken = sasBuilder.ToSasQueryParameters(credentials);
// Construct the full URI, including the SAS token.
UriBuilder fullUri = new UriBuilder()
{
Scheme = "https",
Host = string.Format("{0}.blob.core.windows.net", _blobServiceclient.AccountName),
Path = string.Format("{0}/{1}", containerName, filename),
Query = sasToken.ToString()
};
return fullUri.ToString();
}
public async Task<Document> GetInvoice(byte[] invoiceContent, string invoiceFilename)
{
string filePath = await GetLinkForFile(invoiceFilename);
UploadFile(invoiceFilename, file);
return new Document()
{
Url = filePath
};
}
方法 GetInvoice 由 REST 调用,响应(包含 URL)返回到打开它的浏览器。
【问题讨论】:
-
这可能是因为您没有等待上传操作完成。
-
public async void UploadFile(string filename, byte[] filecontent)也应该是public async Task ...。 -
但是有“AWAIT blobclient.upload...”?
-
就在里面。我认为您必须等待所有异步操作。
-
这只意味着,它在那个上下文中被等待。不在调用上下文中。