Asp.net

在本地電腦上使用 Azure 儲存模擬器時找不到上傳的圖像

  • July 4, 2021

asp.net 4.5、Web 表單、vs2013、身份 2.0、實體框架 6.0

我計劃使用 Azure 儲存 blob 來儲存使用者上傳的圖像。所以我下載了 Azure Storage Emulator 在我的本地機器上進行測試。

似乎容器已正確創建並且圖像已正確保存 - 因為我在執行應用程序時沒有收到任何異常。

但問題是我在我的網頁上看不到這張圖片。調試程式碼,我看到這張圖片的 URI 是

http://127.0.0.1:10000/devstoreaccount1/images/my_sub_folder_2/my_image.jpg

我將此網址粘貼到瀏覽器,IE 告訴我:

The webpage cannot be found 404

鉻告訴我:

This XML file does not appear to have any style information associated with it. The document tree is shown below.
<Error>
<Code>ResourceNotFound</Code>
<Message>
The specified resource does not exist. RequestId:e4b64fa8-5985-4aa4-bfbe-50aabd497537 Time:2014-04-21T07:26:04.4264011Z
</Message>
</Error>

我使用 AzureStorageAccess.CreateContainer() 在儲存中創建一個容器,並使用 AzureStorageAccess.UploadBlob() 將使用者上傳的圖像(流)保存到儲存中。程式碼如下。

public class AzureStorageAccess
{
// create a container in Azure Storage Emulator
   static public void CreateContainer(string containerName)
   {
       CloudStorageAccount storageAccount = CloudStorageAccount
           .Parse("UseDevelopmentStorage=true");
       // CloudConfigurationManager.GetSetting("StorageConnectionString")
       CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
       CloudBlobContainer container = blobClient.GetContainerReference(containerName);
       container.CreateIfNotExists();
   }

// upload a stream to Azure Storage Emulator
   static public void UploadBlob(System.IO.Stream stream, string containerName, string blobRelativeURI, out string blobURI)
   {
       CloudStorageAccount storageAccount = CloudStorageAccount
           .Parse("UseDevelopmentStorage=true");
       // CloudConfigurationManager.GetSetting("StorageConnectionString")
       CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
       CloudBlobContainer container = blobClient.GetContainerReference(containerName);
       CloudBlockBlob blockBlob = container.GetBlockBlobReference(blobRelativeURI);
       blockBlob.UploadFromStream(stream);
       blobURI = blockBlob.Uri.AbsoluteUri;
   }
}

我在 web.config 中有這個連接字元串。最初我使用的是這個連接字元串。後來當我試圖解決這個問題時,我在 stackoverflow 中閱讀了一些我應該使用的文章Parse("UseDevelopmentStorage=true")。您可以看到讀取此連接字元串的程式碼在上面的程式碼中被註釋掉了。

<add key="StorageConnectionString"         value="DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;BlobEndpoint=http://127.0.0.1:10000/devstoreaccount1"
/>  

誰能告訴我有什麼問題?非常感謝!

這是因為容器預設關閉公共讀取訪問。如果您將Public Read Access屬性更改為Container使用Visual Studio Server Explorer

在此處輸入圖像描述

或者,如果您想通過 SDK 在程式碼中執行此操作,請在創建容器之前添加以下行。

       //Create container
       container.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Container });
       container.CreateIfNotExists();

另一種方法是直接通過 Microsoft Azure Storage Explorer。右鍵點擊您的 blob 容器並選擇設置公共訪問級別…

Microsoft Azure 儲存資源管理器

引用自:https://stackoverflow.com/questions/23193060