【问题标题】:How do you check that a container exists in Azure Blob Storage V12如何检查 Azure Blob Storage V12 中是否存在容器
【发布时间】:2020-07-22 12:34:17
【问题描述】:

以前在使用 Azure Blob Storage SDK V11 时,如果您想创建一个容器但不确定该容器是否存在,您可以使用 CreateIfNotExists。

但是在 V12 版本中,CreateIfNotExists 不再可用,我可以从 Microsoft 找到的唯一示例是简单地创建一个容器而不检查它是否已经存在。

那么,有谁知道 V12 中的最佳实践是在尝试创建容器之前检查容器是否存在。

顺便说一下,我正在为 ASP.Net Core 3.1 进行开发。

【问题讨论】:

    标签: azure asp.net-core azure-storage azure-blob-storage


    【解决方案1】:

    在 v12 中,有两种方法可以检查容器是否存在。

    1.

    BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);
    
    //get a BlobContainerClient
    var container = blobServiceClient.GetBlobContainerClient("the container name");
                
    //you can check if the container exists or not, then determine to create it or not
    bool isExist = container.Exists();
    if (!isExist)
    {
        container.Create();
    }
    
    //or you can directly use this method to create a container if it does not exist.
     container.CreateIfNotExists();
    

    你可以直接创建BlobContainerClient,然后使用下面的代码:

    //create a BlobContainerClient 
    BlobContainerClient blobContainer = new BlobContainerClient("storage connection string", "the container name");
        
    //use code below to check if the container exists, then determine to create it or not
    bool isExists = blobContainer.Exists();
    if (!isExist)
    {
       blobContainer .Create();
    }
        
    //or use this code to create the container directly, if it does not exist.
    blobContainer.CreateIfNotExists();
    

    【讨论】:

    • 感谢 Ivan 提供的所有代码示例,这对我的要求很有帮助。
    • 我试过了,但是调用 Exists() 会抛出一个异常,说容器不存在,WTF Microsoft。
    • @Phil,你使用的是什么包和版本?你最好提供一些示例代码:)
    • 部分原因是我,我正在使用 new BlobContainerClient(new Uri("..")); 的 Uri 重载我没有传入 TokenCredential 例如,new DefaultAzureCredential()。该错误可能更有帮助,并暗示授权问题而不是 404。
    • @IvanYang 我已经发布了问题和代码。谢谢!
    【解决方案2】:

    但是在 V12 版本中,CreateIfNotExists 不再可用,并且 我能从微软找到的唯一例子就是简单地创建一个 容器而不检查它是否已经存在。

    我不知道你为什么说CreateIfNotExists is no longer available in version 12 of storage client library。它肯定在BlobContainerClient 类中。这是直接链接:CreateIfNotExists。

        var connectionString = "UseDevelopmentStorage=true";            
        var containerClient = new BlobContainerClient(connectionString, containerName);
        containerClient.CreateIfNotExists();
    

    【讨论】:

    • 感谢 Gaurav 的链接,这很有帮助。我根本找不到使用 CreateIfNotExists 的 V12 的任何代码示例,并且在某个地方读到它不再可用。
    【解决方案3】:

    接受的答案很好。但我通常使用它的异步版本。

    var _blobServiceClient = new BlobServiceClient(YOURCONNECTIONSTRING);
    var containerClient = _blobServiceClient.GetBlobContainerClient(YOURCONTAINERNAME);
    await containerClient.CreateIfNotExistsAsync(Azure.Storage.Blobs.Models.PublicAccessType.BlobContainer);
    

    我使用的版本是 Azure.Storage.Blobs v12.4.1

    【讨论】:

      【解决方案4】:

      我有以下方法获取 SAS 令牌,一切正常。

      private Uri GetUriSasToken()
          {
              string storedPolicyName = null;
              string connectionString = _config.GetConnectionString("BlobConnection");
              BlobContainerClient containerClient = new BlobContainerClient(connectionString, "stock");
      
              // Check whether this BlobContainerClient object has been authorized with Shared Key.
              if (containerClient.CanGenerateSasUri)
              {
                  // Create a SAS token that's valid for one hour.
                  BlobSasBuilder sasBuilder = new BlobSasBuilder()
                  {
                      BlobContainerName = containerClient.Name,
                      Resource = "c"
                  };
      
                  if (storedPolicyName == null)
                  {
                      sasBuilder.ExpiresOn = DateTimeOffset.UtcNow.AddHours(1);
                      sasBuilder.SetPermissions(BlobContainerSasPermissions.Read | BlobContainerSasPermissions.List);
                  }
                  else
                  {
                      sasBuilder.Identifier = storedPolicyName;
                  }
      
                  Uri sasUri = containerClient.GenerateSasUri(sasBuilder);
                  return sasUri;
              }
              else
              {
                  _logger.LogError(@"BlobContainerClient must be authorized with Shared Key credentials to create a service SAS.");
                  return null;
              }
                       
          }
      

      然后,我用下面的代码调用上面的方法:

         BlobServiceClient blobServiceClient = new BlobServiceClient(GetUriSasToken(), null);
              var blobName = _config.GetValue<string>("BlobName");
              var containerName = _config.GetValue<string>("ContainerName");            
              var fileName = _config.GetValue<string>("FileName");            
              var containerClient = blobServiceClient.GetBlobContainerClient(containerName);
      

      有什么方法可以验证容器是否存在?

      我不确定我能做到:

      containerClient.Exists

      我用过但是它返回一个Blob不存在的错误,但是我想先检查一下容器是否存在。

      有人做过吗?

      【讨论】:

      • 我在GetUriSasToken() 方法中看到,您在生成sas_token 时指定了一个容器名称“stock”。那么这个 sas_token 只能用于那个容器“股票”。你最好创建一个帐户级别的 sas_token :)。
      • @IvanYang 找到了你。谢谢你的澄清。你知道如何创建这个帐户级别的令牌吗?我在文档docs.microsoft.com/en-us/rest/api/storageservices/… 中看到了此页面,但我不清楚如何指定帐户级别范围?
      • 能否请您在stackoverflow中添加一个新问题,然后让我知道该问题的链接?请注意,您添加的是答案,而不是问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-16
      • 1970-01-01
      • 2013-07-05
      • 2011-02-08
      • 2018-10-18
      • 1970-01-01
      • 2012-06-17
      相关资源
      最近更新 更多