簡體   English   中英

當將GenerateIfNotExistsCondition用於目標時,為什么StartCopyAsync()會引發409沖突?

[英]Why does StartCopyAsync() throw 409 Conflict when GenerateIfNotExistsCondition used for destination?

如果目標位置不存在,我想將Blob復制到另一個存儲帳戶。 但是我一定會誤讀有關StartCopyAsyncGenerateIfNotExists條件的文檔,因為我認為我可以在一個調用中執行此操作(而不必在另一個調用中檢查目標是否存在),如下所示:

    await _targetClient.StartCopyAsync(
        _schemaBlob, 
        null, 
        _schemaBlob.Name, 
        AccessCondition.GenerateIfNotExistsCondition(), 
        null, 
        ContainerName, 
        cancellationToken);

但是,如果目標Blob存在,則會引發409 Conflict 這不是AccessCondition.GenerateIfNotExistsCondition()參數的要點,以確保在blob存在時該操作什么都不做嗎?

怎么做對?

但是,如果目標Blob存在,則會引發409沖突。 這不是AccessCondition.GenerateIfNotExistsCondition()參數的要點,以確保在blob存在時該操作什么都不做嗎?

在Azure存儲服務方面,它什么也不做,只會返回409狀態代碼。 在您的客戶端,如果返回碼不等於200,則會引發異常。 我建議您在代碼中添加一個try-catch blob,而在catch blob中什么也不做。

try
{
    //put your copy code here
}
catch (StorageException ex)
{
    //If the exception is 409, just skip the exception
    if (!ex.Message.Contains("409"))
    {
        throw ex;
    }
}

否則,您可以在執行復制命令之前檢查目標斑點是否存在。

if (targetBlob.Exists())
{
    //do the copy here
}

將此參數保留為null並初始化為我所做的行為是相同的。

它可能在您的代碼中包含一些錯誤。 有2個AccessCondition,一個用於源blob,另一個用於目標blob。 這是一個示例方法。 如果將目標AccessCondition的值更改為null。 目標Blob將被源Blob覆蓋。

public static async void CopyBlob(Uri sourceBlob, CloudBlockBlob targetBlob, System.Threading.CancellationToken cancellationToken)
{
   string text  = await targetBlob.StartCopyAsync(
       sourceBlob,
       //Source blob access condition, it will check whether the source is exist. If source doesn't exist, a exeception will throw.
       Access​Condition.GenerateIfExistsCondition(),
       //Target blob access condition, it will check whether the target is exist. If target blob exist, 409 error will occur.
       AccessCondition.GenerateIfNotExistsCondition(),
       null,
       null,
       cancellationToken);
}

這是我的測試代碼。 請注意,如果您的源容器是私有的,則需要向StartCopyAsync方法的第一個參數提供帶有SAS的源blob URI。

Uri sourceUri = new Uri("Put your source blob uri with SAS");

string targetConnectionString = "target blob connectionString ";
CloudStorageAccount targetStorageAccount = CloudStorageAccount.Parse(targetConnectionString);
// Create the blob client.
CloudBlobClient targetBlobClient = targetStorageAccount.CreateCloudBlobClient();

CloudBlobContainer targetContainer = targetBlobClient.GetContainerReference("mycontainer2");
CloudBlockBlob targetBlob = targetContainer.GetBlockBlobReference("text1.txt");

CopyBblob(sourceUri, targetBlob, new System.Threading.CancellationToken());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM