【问题标题】:Serving images from Azure Blob Storage in dot net core在 dot net core 中提供来自 Azure Blob 存储的图像
【发布时间】:2017-05-16 05:35:36
【问题描述】:

我正在尝试编写一些中间件来通过代理服务 Azure Blob。正在调用处理程序,正在检索 blob,但未显示我的图像。

我编写了一个服务来连接到存储帐户并创建一个 Blob 客户端。我编写了使用服务的中间件,然后下载请求的 blob 并将其写入响应。通常,我希望将 blob 作为字节数组或流下载并将其写入 OutputStream,这似乎不是使用 .net 核心中的新 httpContext 的选项。

我的中间件:

namespace SampleApp1.WebApp.Middleware
{
    public class BlobFileViewHandler
    {
        public BlobFileViewHandler(RequestDelegate next)
        {
        }

        public async Task Invoke(HttpContext httpContext, IBlobService svc)
        {
            string container = httpContext.Request.Query["container"];
            string itemPath = httpContext.Request.Query["path"];

            Blob cbb = await svc.GetBlobAsync(container, itemPath);

            httpContext.Response.ContentType = cbb.ContentType;
            await httpContext.Response.Body.WriteAsync(cbb.Contents, 0, cbb.Contents.Length);            
        }
    }

    // Extension method used to add the middleware to the HTTP request pipeline.
    public static class BlobFileViewHandlerExtensions
    {
        public static IApplicationBuilder UseBlobFileViewHandler(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<BlobFileViewHandler>();
        }
    }
}

我在 Startup 中使用 Map 函数调用中间件,如下所示:

app.Map(new PathString("/thumbs"), a => a.UseBlobFileHandler());

最后,我尝试在测试页面上使用该处理程序,如下所示:

   &lt;img src="~/thumbs?qs=1" alt="thumbtest" /&gt;

当我调试时,我可以看到所有正确的部分都被击中,但图像永远不会加载,我只是得到以下信息:

我觉得我错过了一些简单的东西,但我不确定那是什么。我正在使用 NetCoreApp 1.1 版。

【问题讨论】:

  • 我试过你的解决方案,因为这是我需要的,但是下面一行 app.Map(new PathString("/thumbs"), a => a.UseBlobFileHandler()) 有问题;你能做更多的解释吗?谢谢
  • app.Map() 只是使管道短路,并让运行时知道对给定路径的任何请求都将由指示的中间件处理。这就是 .net core 中 HttpHandler 的建模方式。
  • 我明白这一点,但它向我显示了 a => a.UseBlobFileHandler() 的错误
  • 我更新了我的问题,为您提供了我当前处理程序的全貌。也许这会回答你关于扩展方法使用的问题。
  • 谢谢,我成功了。

标签: asp.net-core asp.net-core-mvc asp.net-core-middleware


【解决方案1】:

我想我有点过早了,因为您似乎可以写入 OutputStream,只是引用方式略有不同。以下是我在中间件中尝试的工作实现:

public class BlobFileHandler
{
    public BlobFileHandler(RequestDelegate next)
    {
    }

    public async Task Invoke(HttpContext httpContext)
    {
        string container = "<static container reference>";
        string itemPath = "<static blob reference>";
        //string response;
        IBlobService svc = (IBlobService)httpContext.RequestServices.GetService(typeof(IBlobService));

        CloudBlockBlob cbb = svc.GetBlob(container, itemPath);

        httpContext.Response.ContentType = "image/jpeg";//cbb.Properties.ContentType;            
        await cbb.DownloadToStreamAsync(httpContext.Response.Body);
    }
}

【讨论】:

    猜你喜欢
    • 2012-04-08
    • 2021-07-30
    • 2017-06-24
    • 1970-01-01
    • 2019-04-03
    • 2023-01-03
    • 2020-07-14
    • 2020-10-04
    • 1970-01-01
    相关资源
    最近更新 更多