【问题标题】:How do I return an image to a view from a private Azure Blob Stroage account in ASP.NET Core?如何从 ASP.NET Core 中的私有 Azure Blob 存储帐户将图像返回到视图?
【发布时间】:2020-07-18 11:29:19
【问题描述】:

我已将我的 Azure blob 存储容器设置为私有,并且我有一个在我的 asp.net 核心应用程序中定义的共享访问密钥。对于列出 blob 存储内容等工作,它运行良好,但现在我发现自己需要带回一个图像文件以显示在我的视图中。问题是当我返回 blob 时,是的,我可以在控制器中访问它,但它只是将字符串返回到它的位置,在没有访问密钥的情况下访问该位置会返回错误 Resource not found,这是预期的。

我的问题是,如何将需要共享访问密钥的图像 blob 返回到我的视图?到目前为止,这是我的代码,它仅将 Uri 作为字符串返回,由于上述原因,它没有任何用处。我需要下载图像并临时存储它吗?

汽车控制器使用

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);
    }

【问题讨论】:

    标签: c# asp.net-core blob azure-blob-storage


    【解决方案1】:

    要从私有容器中读取,您需要在 blob 或至少具有 Read 权限的 blob 容器上创建 Shared Access Signature

    这是您可以使用的代码。在此,我正在使用 Read 权限在 blob 上创建一个 SAS 令牌,该权限将在创建后 1 分钟后过期。

            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
            };
    

    【讨论】:

      猜你喜欢
      • 2019-03-04
      • 2020-11-12
      • 1970-01-01
      • 2020-07-14
      • 2017-03-26
      • 2020-01-25
      • 2020-07-18
      • 2021-01-16
      • 2018-12-17
      相关资源
      最近更新 更多