2012-11-01 25 views
0

我想在C#中使用PutBlockList方法將電影塊上傳到Azure blob。我一直在編寫一個測試代碼,問題是當我使用MD5來保證數據的完整性並且故意破壞導致不同MD5值的數據時,服務器不會拒絕上載並接受它,而在一個正確的代碼必須被拒絕。通過PutBlockList方法在C#和MD5中上傳到blob檢查

var upload = Take.CommitBlocks(shot,takeId,data); 
.... 
blob.Properties.ContentMD5 = md5; 
return Task.Factory.FromAsync(blob.BeginPutBlockList(ids,null,null),blob.EndPutBlockList); 

在我的測試方法中,我故意破壞數據,但系統仍然接受數據。我怎樣才能解決這個問題 ?在一個正確的代碼中,我應該會收到Error400,但是我什麼也沒得到。

回答

0

我已經晚了幾年,但從我所看到的情況來看,這個功能仍然沒有內置到API和SDK(Assembly Microsoft.WindowsAzure.Storage,Version = 8.1.4.0)中。這就是說,這裏是我的解決方法:

using Microsoft.WindowsAzure.Storage; 
using Microsoft.WindowsAzure.Storage.Blob; 
using System; 
using System.IO; 
using System.Threading.Tasks; 

/// <summary> 
/// Extension methods for <see cref="CloudBlockBlob"/> 
/// </summary> 
public static class CloudBlockBlobExtensions 
{ 
    /// <summary> 
    /// Attempts to open a stream to download a range, and if it fails with <see cref="StorageException"/> 
    /// then the message is compared to a string representation of the expected message if the MD5 
    /// property does not match the property sent. 
    /// </summary> 
    /// <param name="instance">The instance of <see cref="CloudBlockBlob"/></param> 
    /// <returns>Returns a false if the calculated MD5 does not match the existing property.</returns> 
    /// <exception cref="ArgumentNullException">If <paramref name="instance"/> is null.</exception> 
    /// <remarks>This is a hack, and if the message from storage API changes, then this will fail.</remarks> 
    public static async Task<bool> IsValidContentMD5(this CloudBlockBlob instance) 
    { 
     if (instance == null) 
      throw new ArgumentNullException(nameof(instance)); 

     try 
     { 
      using (var ms = new MemoryStream()) 
      { 
       await instance.DownloadRangeToStreamAsync(ms, null, null); 
      } 
     } 
     catch (StorageException ex) 
     { 
      return !ex.Message.Equals("Calculated MD5 does not match existing property", StringComparison.Ordinal); 
     } 

     return true; 
    } 
} 

〜乾杯