切换到 Azure.Storage.Queues 后 Azure 函数中的模型绑定问题

Posted

技术标签:

【中文标题】切换到 Azure.Storage.Queues 后 Azure 函数中的模型绑定问题【英文标题】:Model Binding Issue in Azure Function After Switching to Azure.Storage.Queues 【发布时间】:2021-03-10 11:44:30 【问题描述】:

我在后端使用带有队列触发器的 Azure Functions,到目前为止,我一直在使用 Microsoft.WindowsAzure.Storage 包来处理所有 Azure 存储操作,即队列、blob 等。有了这个包,我只需将MyQueueRequest 对象发送到我的队列,一切正常。

由于Microsoft.WindowsAzure.Storage 包已被弃用,我切换到Azure.Storage.Queue 并且我的Azure 函数开始抛出以下错误:

Microsoft.Azure.WebJobs.Host:异常绑定参数“消息”。 System.Private.CoreLib:输入不是有效的 Base-64 字符串,因为它 包含非 base 64 字符、两个以上的填充字符,或 填充字符中的非法字符。

我发现这篇文章表明新库需要将 JSON 对象编码为 Base64 (https://briancaos.wordpress.com/2020/10/16/sending-json-with-net-core-queueclient-sendmessageasync/)。

到目前为止,我什至从未将我的 MyQueueRequest 对象序列化为 JSON。模型绑定器会自动为我处理这些问题。

这是否意味着,在将消息发送到我的队列之前,我需要先序列化MyQueueRequest 对象,然后对其进行Base64 编码,然后在我的 Azure Functions 中反转该过程?

【问题讨论】:

【参考方案1】:

是的,对于这个新包,您需要这样做。我在尝试将 POCO 添加到队列时遇到了同样的问题。我使用与您引用的文章类似的代码。

我使用下面的代码来处理这个:

await queue.SendMessageAsync(Base64Encode(JsonSerializer.Serialize(myObject)));

Base64Encode 在哪里:

    private string Base64Encode(string plainText)
    
        var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
        return Convert.ToBase64String(plainTextBytes);
    

确保它也是 UTF-8。我在此示例中使用 System.Text.Json,但 Newtonsoft 也可以。

【讨论】:

谢谢!感谢您的回复!

以上是关于切换到 Azure.Storage.Queues 后 Azure 函数中的模型绑定问题的主要内容,如果未能解决你的问题,请参考以下文章

访问 Azure 存储帐户中的所有队列

如何切换到root用户

在Ubuntu下如何切换到超级用户

如何切换到root用户

如何切换到 root 用户

linux环境下如何快速切换到用户tom的主目录