【问题标题】:How to display images in .cshtml page from Private Azure Storage in MVC?如何在 MVC 中的私有 Azure 存储中显示 .cshtml 页面中的图像?
【发布时间】:2020-09-22 17:54:56
【问题描述】:

我在检查 html 页面时遇到以下错误:

<Error>
    <Code>AuthorizationFailure</Code>
    <Message>This request is not authorized to perform this operation.
           RequestId:7b853423-101e-0015-51e5-905acd000000
           Time:2020-09-22T13:38:05.2479851Z
    </Message>
</Error>

我在 web.config 文件中为 Azure 连接字符串创建了密钥,用于访问 azure 存储 blob 的写入方法使私有为公共:

public ActionResult BlobManager(string ContainerName = "images")
{
    string ConnectionString = ConfigurationManager.AppSettings["AzureStorageConnectionString"].ToString();
    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConnectionString);
    CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();
    blobContainer = cloudBlobClient.GetContainerReference(ContainerName);

    //Make available to everyone
    blobContainer.SetPermissions(new BlobContainerPermissions{
        PublicAccess = BlobContainerPublicAccessType.Blob
        });
    }

这是我的控制器方法:

[HttpGet]
public JsonResult GetImageList(int TaskID)
{
    var data = (from d in _context.ImgTable
                where (d.Taskid == TaskID )
                select new
                {
                    d.ImageID,
                    d.Taskid,
                    d.ImagePath,
                }).ToList();
    return Json(data, JsonRequestBehavior.AllowGet);
}

请帮助您如何走得更远。我想在 html 页面中显示图像。 我从下拉列表中选择Taskid,单击它会在html表中显示与该taskid相关的图像。下面是js函数:

$.ajax({
        type: 'GET',
        url: '@Url.Action("GetImageList")',
        datatype: JSON,
        data: {
                'TaskID': $("#tasklist").val()                //getting selected TaskID from dropdown
        },
        success: function (data) {
                 var row_no = 1;
                 $.each(data, function (i, item) {
             
                 var path = "https://abcdatastorage.blob.core.windows.net/task/";     //azure storage url
                 var img = item.ImagePath;                                            //getting imagepath from local db
                     img = img.replace(/\s+/g, '%20');
                 var img1 = img.split('\\');
                     img = (path + img1[5]);                                          //joining above url to get complete url to bind with <img src>

            
                + "<td id='ItemId" + row_no + "' >" + item.ID + "</td>"               // displaying image id in html table

                "<td>"
                + "<div><img id='Image" + row_no + "' src=" + img + " class='img-fluid img-thumbnail' alt='' style='width:500px; height:350px;' />"  // display image for that imageid
                + "</div></td > "
     });

我可以直接在 html 中传递 azure storage url 吗?我可以访问和显示图像吗? 如果 Azure 存储是私有的,图像将如何显示?

下面是我通过上面用 js 编写的连接 url 获得的 src。但是看不到图片。

<div>
    <img src='https://abcimages.blob.core.windows.net/images/418;1488163937486;d%20V%20Phase%205.0%20kV.jpg' class='img-fluid img-thumbnail' alt='' style='width:500px; height:350px;' />
</div>

请帮忙解决。如何通过代码访问私有 Azure 存储并显示图像。

【问题讨论】:

  • 您的问题解决了吗?我的方法对你有帮助吗?
  • 是的,你的方法很有帮助
  • 能否请您指导我提出的这个问题与这个问题有点相似,但需要新方法:stackoverflow.com/questions/64304969/…
  • 你使用 azure web app 吗?
  • 如果是,请修改标签,我稍后会检查。

标签: model-view-controller azure-blob-storage


【解决方案1】:

我有一个简单的方法来实现这个功能,你的代码不需要做很多修改。

我的建议是你写一个通用的GetAccountSASToken 方法。如果需要安全验证,建议验证通过后调用该方法,以便生成生成的sas token并附加到img URL。

您可以阅读官方文档Create an account SAS with .NET。

static void Main(string[] args)
{
    Console.WriteLine("Hello World!");
    Console.WriteLine(GetAccountSASToken());
}
public static string GetAccountSASToken()
{
    // To create the account SAS, you need to use Shared Key credentials. Modify for your account.
    const string ConnectionString = "DefaultEndpointsProtocol=**fix=core.windows.net";
    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConnectionString);

    // Create a new access policy for the account.
    SharedAccessAccountPolicy policy = new SharedAccessAccountPolicy()
    {
        Permissions = SharedAccessAccountPermissions.Read | SharedAccessAccountPermissions.Write | SharedAccessAccountPermissions.List,
        Services = SharedAccessAccountServices.Blob | SharedAccessAccountServices.File,
        ResourceTypes = SharedAccessAccountResourceTypes.Service | SharedAccessAccountResourceTypes.Container | SharedAccessAccountResourceTypes.Object,
        SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24),
        Protocols = SharedAccessProtocol.HttpsOnly
    };

    // Return the SAS token.
    return storageAccount.GetSharedAccessSignature(policy);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-04
    • 1970-01-01
    • 2021-02-02
    相关资源
    最近更新 更多