代码之家  ›  专栏  ›  技术社区  ›  Ole Albers

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

  •  1
  • Ole Albers  · 技术社区  · 5 年前

    当我这样做的时候,我经常(但不是总是)检索一个404,这个资源不存在。几秒钟后刷新页面时,将正确检索到该页面。

    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

    1 回复  |  直到 5 年前
        1
  •  2
  •   Gaurav Mantri    5 年前

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

    _azureStorageRepository.UploadFile(invoiceFilename, file);
    

    请将此更改为:

    await _azureStorageRepository.UploadFile(invoiceFilename, file);
    

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

    另外,更改 UploadFile 方法来自 public async void UploadFile public async Task UploadFile 正如@Fildor在评论中提到的。