Collega
Collega

Reputation: 442

Upload blob to Azure and give public read access C#

I'm trying to upload an image to Azure blob storage to view later in my application. However, when I uploaded my image I can not view the image using the link of my blob as I think the file-view permissions are not set correctly. But, I do not know how to set these in code.

I have found a question with an answer that is similar, but it's so outdated that it does not work like that anymore.

(Link of the old similar question)

In the following block you can find a piece of my code that creates a container (if it does not exist => create one), in eather way, if it exists or not, yet it should be set accessible for anyone to read/view the uploaded blob.

        public async Task<BlobContainerClient> CreateContainerAsync(string containerName, CancellationToken cancellationToken = default)
    {
        if (string.IsNullOrWhiteSpace(containerName))
            throw new ArgumentException($"'{nameof(containerName)}' cannot be null or whitespace.", nameof(containerName));

        var container = new BlobContainerClient(_connectionString, containerName);
         //Here I want to set the access policy but I'm not sure on how to implement it
        //await container.SetAccessPolicyAsync(PublicAccess = Azure.Storage.Blobs.Models.PublicAccessType.Blob);

        await container.CreateIfNotExistsAsync(cancellationToken: cancellationToken);
        return container;
    }

Thanks in advance for any tips!

Upvotes: 0

Views: 958

Answers (1)

Jochem Van Hespen
Jochem Van Hespen

Reputation: 414

As requested ^^

CreateIfNotExistsAsync has an overload which allows you to pass BlobContainerPublicAccessType.

This Enum enables you to specific the access type of the created containers.

Alternatively you can also adjust this through Azure in case your container has already been created and you have the required access (check through Access Control (IAM)) by navigating to the container and then pressing following button:

Change access level

You will see the options it gives you will map directly to the BlobContainerPublicAccessType

Upvotes: 3

Related Questions