繁体   English   中英

上传文件到 Azure Blob 存储后一小段时间出现 404

[英]404 for a small period of time after uploading file to Azure Blob Storage

我将附件上传到 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 方法由GetInvoice调用,响应(包含 URL)返回到打开它的浏览器。

如果您注意到,您不会在此处等待上传操作完成:

_azureStorageRepository.UploadFile(invoiceFilename, file);

请将其更改为:

await _azureStorageRepository.UploadFile(invoiceFilename, file);

而且您不应该看到 404 错误。 Azure Blob 存储是强一致的。

此外,如@Fildor 在评论中提到的,将UploadFile方法从public async void UploadFile更改为public async Task UploadFile

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM