Reputation: 2184
I've set my Azure blob storage containers to private and I have a shared access key that I've defined within my asp.net core application. For jobs such as listing the contents of the blob storage, it works well but now I find myself needing to bring back an image file to show within my view. The problem is that when I return the blob, yes I can access it in the controller but it just returns the string to its location, accessing that location without the access key returns the error Resource not found
, which is expected.
My question is, how do I return an image blob which requires the shared access key to my view? Here is my code so far which, only returns the Uri as a string which isn't any use for the above-mentioned reason. Do I need to download the image and store it temporarily or something?
CarController Usings
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
CarController.cs
[HttpGet]
public IActionResult Edit(int id)
{
var car = _carService.GetCar(id);
string strContainerName = "uploads";
string filePrefix = "car/" + id + "/car-image.jpg";
var filelist = new List<BlobListViewModel>();
BlobServiceClient blobServiceClient = new BlobServiceClient(accessKey);
BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(strContainerName);
//Get the specific image
var blob = containerClient.GetBlobClient(filePrefix);
//I'm binding to a view model as a string, which, as I say, doesn't work for security reasons.
var data = new BlobListViewModel {
FileName = blob.Uri.ToString()
};
return View(data);
}
Upvotes: 1
Views: 1395
Reputation: 136334
To read from a private container, you would need to create a Shared Access Signature
on either the blob or the blob container with at least Read
permission.
Here's the code you can use. In this, I am creating a SAS Token on the blob with Read
permission that will expire after 1 minute from the time it was created.
BlobSasBuilder blobSasBuilder = new BlobSasBuilder()
{
BlobContainerName = strContainerName,
BlobName = filePrefix,
ExpiresOn = DateTime.UtcNow.AddMinutes(1),
};
blobSasBuilder.SetPermissions(BlobAccountSasPermissions.Read);
var sasToken = blobSasBuilder.ToSasQueryParameters(new Azure.Storage.StorageSharedKeyCredential(accountName, accountKey)).ToString();
var blob = containerClient.GetBlobClient(filePrefix);
var blobSasUrl = blob.Uri.ToString() + "?" + sasToken;
//I'm binding to a view model as a string, which, as I say, doesn't work for security reasons.
var data = new BlobListViewModel
{
FileName = blobSasUrl
};
Upvotes: 2