我在后端使用带有队列触发器的 Azure Functions,到目前为止,我一直在使用 Microsoft.WindowsAzure.Storage
包来处理所有 Azure 存储操作,即队列、blob 等.使用这个包,我只需将 MyQueueRequest
对象发送到我的队列,一切就正常了。
由于 Microsoft.WindowsAzure.Storage
包已被弃用,我切换到 Azure.Storage.Queue
并且我的 Azure 函数开始抛出以下错误:
Microsoft.Azure.WebJobs.Host: Exception binding parameter 'message'. System.Private.CoreLib: The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.
我发现这篇文章表明新库需要使用 Base64
编码 JSON
对象 ( https://briancaos.wordpress.com/2020/10/16/sending-json-with-net-core-queueclient-sendmessageasync/ )。
到目前为止,我实际上从未将 MyQueueRequest
对象序列化为 JSON
。模型绑定(bind)器自动为我处理了这个问题。
这是否意味着,在将消息发送到我的队列之前,我需要首先序列化 MyQueueRequest
对象,然后对其进行 Base64
编码,然后反转该过程我的 Azure 函数?
最佳答案
是的,对于这个新包,您需要执行此操作。当我尝试将 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 - 切换到 Azure.Storage.Queues 后 Azure Function 中的模型绑定(bind)问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65041620/