简体   繁体   中英

How can I get an Azure CloudBlockBlob from a storage URL with a SAS?

I have am trying to refactor our MVC code which has a lot of pages which make use of download url which point at a blob with a SAS. It would be great to be able to pass the Url to the controller and use it to locate the associated Blob. Eg Have an action that has the download Url as its only input parameter. I can also create a link helper that only shows the delete link if the SAS exposes delete etc.

It would be a great help if I could pass the Url to Azure and get a CloudBlockBlob in return. So I could delete it, update it, get metadata etc.

The only way I can do it presently is resorting to using techniques like

     var deleteBlobRequest = BlobRequest.Delete(new Uri(fileUrl), 30, null, DeleteSnapshotsOption.IncludeSnapshots, "");
     deleteBlobRequest.GetResponse().Close();

This works but it seems very odd.

I can't figure out the code to get a CloudBlockBlob from the Uri.

Any ideas? I am presently using Azure Storage 1.7

You don't have to do anything special. If you construct a blob with a SAS Uri, storage client library takes care of this for you. For example, take this code:

        CloudBlockBlob cloudBlockBlob = new CloudBlockBlob("http://127.0.0.1:10000/devstoreaccount1/temp/sastest.txt?sr=b&st=2013-01-25T04%3A28%3A09Z&se=2013-01-25T05%3A28%3A09Z&sp=rwd&sig=jIWWFwZ6MXaL6FD%2F2%2FpqPl1g4f0ElFrr1fKNg5U%2FAkg%3D");
        cloudBlockBlob.Delete();

This would work just fine.

Here is the code to get the permissions of a SAS key (supposing the blobUrl is an url with the SAS key):

// Get permssions for current SAS key.
var queryString = HttpUtility.ParseQueryString(blobUrl);
var permissionsText = queryString["sp"];
var permissions = SharedAccessBlobPermissions.None;
if (permissionsText.Contains("w"))
    permissions = permissions | SharedAccessBlobPermissions.Write;
if (permissionsText.Contains("r"))
    permissions = permissions | SharedAccessBlobPermissions.Read;
if (permissionsText.Contains("d"))
    permissions = permissions | SharedAccessBlobPermissions.Delete;
if (permissionsText.Contains("l"))
    permissions = permissions | SharedAccessBlobPermissions.List;

And this will get an ICloudBlob based on an URL with SAS key (supposing the blobUrl is an url with the SAS key):

// Get the blob reference.
var blobUri = new Uri(blobUrl);
var path = String.Format("{0}{1}{2}{3}", blobUri.Scheme, Uri.SchemeDelimiter, blobUri.Authority, blobUri.AbsolutePath);
var blobClient = new CloudBlobClient(new Uri(path), new Microsoft.WindowsAzure.Storage.Auth.StorageCredentials(blobUri.Query));
ICloudBlob blobReference = blobClient.GetBlobReferenceFromServer(new Uri(path));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM