简体   繁体   中英

Azure SAS download blob

I'm trying to download a blob with SAS and kinda clueless right now.

I'm listing all the belonging user blobs in a view. When a user clicks on the blob its supposed to start downloading it.

Here is the view:

@foreach (var file in Model)
{
        <a href='@Url.Action("GetSaSForBlob", "Folder", new { blob = file })>
        </a>
}

Here is my two functions located in "Folder" controller.

public void GetSaSForBlob(CloudBlockBlob blob)
{
    var sas = blob.GetSharedAccessSignature(new SharedAccessBlobPolicy()
    {
        SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-5),
        SharedAccessExpiryTime = DateTime.UtcNow.AddHours(3),
        Permissions = SharedAccessBlobPermissions.Read | SharedAccessBlobPermissions.Write,
    });

    DownloadFileTest(string.Format(CultureInfo.InvariantCulture, "{0}{1}", blob.Uri, sas));

    //return string.Format(CultureInfo.InvariantCulture, "{0}{1}", blob.Uri, sas);
}

static void DownloadFileTest(string blobSasUri)
{
    CloudBlockBlob blob = new CloudBlockBlob(new Uri(blobSasUri));
    using (MemoryStream ms = new MemoryStream())
    {
        blob.DownloadToStream(ms);
        byte[] data = new byte[ms.Length];
        ms.Position = 0;
        ms.Read(data, 0, data.Length);
    }
}
  1. What should i be passing from my view to GetSasForBlob? At the moment CloudBlockBlob blob is null.

  2. Am i missing any code in function DownloadFileTest?

  3. Should i be calling DownloadFileTest directly from GetSasForBlob?

  4. How can i protect these two functions so people cant access them outside the view? They are both static functions now. I'm guessing that is not safe?

1, What the value is of your file in your view. I don't think MVC can create CloudBlockBlob object based on the file you provided. So this might be the reason you got null of your CloudBlockBlob .

2, In your DownloadFileTest you just download the binaries of the blob into the memory stream in your server and that's all. If you need to let user download it to local disk you need to put the binaries into Response.Stream . You can just use something like blob.DownloadToStram(Response.Stream) .

3, That's up to you. You can merge them in the same method if you want.

4, If you want user to download blob through your web front (website or web service), as what you are doing now, you need to set your blob container as private and secure your website or web service by using something loke [Authorize] attribute. Basically in your case you really don't need to use SAS at all because all download requests are performed through your web front.

Hope this helps a bit.

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