访问blob uri时的ResourceNotFound

时间:2017-06-27 12:43:39

标签: c# azure azure-storage azure-storage-blobs azure-blob-storage

我正在尝试通过Azure Blob存储中的URL检索图像,但它找不到它,这就是我得到的:

enter image description here

我的代码如下:

public async Task<bool> UploadFileAsync(string containerReference, string blobReference, string route)
    {
        CloudBlobContainer container = blobClient.GetContainerReference(containerReference);
        container.CreateIfNotExists();
        CloudBlockBlob blob = container.GetBlockBlobReference(blobReference);

        try
        {
            using (var fileStream = System.IO.File.OpenRead(route))
            {
                await blob.UploadFromStreamAsync(fileStream);
            }
        }
        catch (System.Exception)
        {
            return false;
        }

        return true;
    }

成功将文件上传到blob:

enter image description here

然后我尝试检索其URL以直接访问它:

public string GetBlobUrl(string containerReference, string blobReference)
    {
        CloudBlobContainer container = blobClient.GetContainerReference(containerReference);
        CloudBlockBlob blob = container.GetBlockBlobReference(blobReference);

        return blob.Uri.ToString();
    }

我做错了什么?

2 个答案:

答案 0 :(得分:2)

如果容器不存在,您的代码包含一行来创建容器。默认情况下,blob容器创建为私有容器:

  

默认情况下,新容器是私有的,这意味着您必须指定存储访问密钥才能从此容器中下载blob。

如果要公开容器中的文件,可以使用以下代码将容器设置为公共:

# In your tasks
- name: start container current
  docker_container:
    name: "{{ item }}"
    image: "{{ item }}:{{ docker_containers_config[item].version }}"
    state: started
    recreate: true
    ports:
      - "{{ docker_containers_config[item].ports }}"
    volumes:
      - /opt/application/i99/{{ item.type }}/logs:/opt/application/i99/{{ item.type }}/logs
    env_file: /opt/application/i99/{{ docker_containers_config[item].type }}/{{ item }}/{{ item }}-PreProd-config.list
    env:
        LOG_FILE_WS: "/opt/application/i99/{{ docker_containers_config[item].type }}/logs/{{ hostname }}_WS.log"
  with_items: "{{ RCD_APIS.split(',') }}"

有关详细信息,请参阅Get started with Azure Blob storage using .NET。上面的描述和代码取自该页面的“创建容器”段落。

答案 1 :(得分:2)

默认情况下,只能由存储帐户所有者访问容器及其blob。如果您希望私有容器中的blob可以通过匿名请求读取,则可以grant public read access for blobs。此外,正如David Makogon在评论中提到的那样,你也可以grant temporary public access to a private blob via shared access signature

CloudBlobContainer container = cloudBlobClient.GetContainerReference("mycontainer");   
CloudBlockBlob blob = container.GetBlockBlobReference("testimg.PNG");

SharedAccessBlobPolicy sasConstraints = new SharedAccessBlobPolicy();
sasConstraints.SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5);
sasConstraints.SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddDays(7);
sasConstraints.Permissions = SharedAccessBlobPermissions.Read;


string sasBlobToken = blob.GetSharedAccessSignature(sasConstraints);
string URL = blob.Uri + sasBlobToken;