首页 > 解决方案 > Azure Web App Bot - 访问本地资源

问题描述

我的 Web App Bot 应该根据请求返回图像。图像位于文件夹中的 .csproj 中,具有以下配置

在此处输入图像描述

将图像发送给用户的源代码

        var imgMessage = context.MakeMessage();

        var attachment = new Attachment();
        attachment.ContentUrl = $"{HttpContext.Current.Request.Url.Scheme}://{HttpContext.Current.Request.Url.Authority}/Resources/{InvocationName}/{InvocationNameExtension}.jpg";
        attachment.ContentType = "image/jpg";
        attachment.Name = "Image";

        context.PostAsync(attachment.ContentUrl);

虽然它在本地工作,但在发布到 Azure 云后就无法工作。但是,Azure 云的路径类似于:h ttps://xxxx.azurewebsites.net/Resources/img/Cafeteria.jpg

FTP 上传确实包含该文件

2>Adding file (xxxx\bin\Resources\img\Cafeteria.jpg).

该文件在服务器上,但无法访问。我应该如何包含位于 .csproj 中的图像?由于独立性,我不想引用外部 URL。

标签: azurebots

解决方案


将构建操作更改为:“嵌入式资源”。

        string resourceFile = ResourceManager.FindResource(InvocationName, InvocationNameExtension);
        string resourceFileExtension = ResourceManager.GetResourceExtension(resourceFile);

        var attachment = new Attachment();
        attachment.ContentUrl = BuildImageUrl(resourceFile, resourceFileExtension);
        attachment.ContentType = $"image/{resourceFileExtension}";



    private string ConvertToBase64(string resourceFile) => Convert.ToBase64String(ResourceManager.GetBytes(resourceFile));

    private string BuildImageUrl(string resourceFile, string resourceFileExtension) => "data:image/" + resourceFileExtension + ";base64," + ConvertToBase64(resourceFile);

使用这种方法,我通过 base64 直接将图像的内容发送给用户。奇迹般有效


推荐阅读