Can't programmatically set permissions to blob

2019-07-15 17:22发布

问题:

After creating a blob container with CreateIfNotExists(), I immediately call SetPermissions() to allow users public access to the blobs in the container, but not to the container itself.

Like so:

CloudBlobContainer pdfContainer = blobClient.GetContainerReference(ContainerName.PDFs);

if (pdfContainer.CreateIfNotExists())
    pdfContainer.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });

The container is created successfully, but when I log in to the Azure portal, the blob container permission is Private.

Am I missing an additional call to commit the permission changes? None of the examples that I've looked at seem to show that and I don't see anything in the documentation either. I'm using v2.0 of the Azure SDK.

UPDATE:

It looks like CreateIfNotExists() is always returning false. I pried the assembly open in Reflector and found that it was catching a (409) Conflict HTTP error and swallowing the exception. This appears to be an issue with either the SDK or the server-side REST implementation. Even though the container does not exist and the container creation succeeds, a 409 is still returned from the server.

It seems like the best thing to do is call CreateIfNotExists() and ignore the return value for now.

Also, it is not necessary to call GetPermissions() before calling SetPermissions().

回答1:

This works for me (I run it on app start-up):

var blobContainer = GetPhotoBlobContainer();  
blobContainer.CreateIfNotExists();  
var perm = new BlobContainerPermissions();  
perm.PublicAccess = BlobContainerPublicAccessType.Blob;  
blobContainer.SetPermissions(perm); 


回答2:

You can either retrieve the container permissions via CloudBlobContainer.GetPermissions or create new container permissions, then you can set the BlobContainerPermissions.PublicAccess property.

BlobContainerPermissions perms = pdfContainer.GetPermissions(); // get existing permissions
perms.PublicAccess = BlobContainerPublicAccessType.Blob; // blob public access
pdfContainer.SetPermissions(perms);

// or create new permissions
BlobContainerPermissions perms =  new BlobContainerPermissions();
perms.PublicAccess = BlobContainerPublicAccessType.Blob; // blob public access
pdfContainer.SetPermissions(perms);