簡體   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