从函数应用加载和执行 Azure Blob 容器中的代码?

问题描述 投票:0回答:1

我有一个多租户应用程序,它将每个租户的某些自定义程序集存储在他们的 Azure 存储帐户中的 blob 中。这些程序集包含自定义代码,用于为登录的特定租户运行报告。

我认为最直接的方法是让 Azure 函数将 DLL 下载到它的本地工作区并从那里加载和执行(我们使用 MEF 来执行此操作)。

Azure 函数或 Web 应用程序是否可以直接从该 blob 容器执行代码?

Azure 网站可以用完 Azure 存储 很好奇 azure 函数是否可以远程动态加载和运行这些程序集。显然,这样做存在安全风险,但解决方法是什么?

此外,Azure 函数实际上是从 blob 存储中执行代码的,我是在与 Azure 代表在支持电话上聊天时发现的,尽管我不知道他们是怎么做到的,也没有做过 POC。

在运行 POC 之前看看这是否可行。

c# azure-functions azure-blob-storage mef
1个回答
0
投票

您可以简单地从 blob 存储中下载一个 blob 作为字节数组,将其加载为程序集,然后使用它。

这是静态函数的简单实现:

[FunctionName("LoadDll")]
public static async Task<object> RunDll(
    [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req,
    ILogger log)
{
    var containerName = "dlls";
    var filename = "ClassLibrary1.dll";

    // Connect to Storage Account (in case of local development – Azurite)
    var blobServiceClient = new BlobServiceClient("AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;DefaultEndpointsProtocol=http;BlobEndpoint=http://127.0.0.1:10000/devstoreaccount1;QueueEndpoint=http://127.0.0.1:10001/devstoreaccount1;TableEndpoint=http://127.0.0.1:10002/devstoreaccount1;");

    var blobContainerClient = blobServiceClient.GetBlobContainerClient(containerName);
    var blobClient = blobContainerClient.GetBlobClient(filename);
    // Read the assembly file from the Blob Storage
    var stream = await blobClient.OpenReadAsync();

    using var memoryStream = new MemoryStream();
    await stream.CopyToAsync(memoryStream);
    // Read it to a byte array
    var assemblyBytes = memoryStream.ToArray();

    // Load the assembly from the byte array
    var assembly = Assembly.Load(assemblyBytes);

    // Find a class
    var class1Type = assembly.GetType("ClassLibrary1.Class1");
    // Find a method in the class
    var method = class1Type.GetMethod("GetInt");

    // Instantiate the class
    var obj = Activator.CreateInstance(class1Type);
    // Call the method
    var result = method.Invoke(obj, null);
    return result;
}

我创建了一个类库项目

ClassLibrary1
并定义了一个类:

namespace ClassLibrary1
{
    public class Class1
    {
        public int GetInt()
        {
            return 1;
        }
    }
}

然后我将它上传到 Azurite(本地存储帐户模拟器)到 blob 容器

dlls


结果

当我运行 Azure Function 应用程序并在浏览器中打开 URL

http://localhost:7208/api/LoadDll
时,结果是:

© www.soinside.com 2019 - 2024. All rights reserved.