问题描述
在 C# Azure Function使用 Service Bus 作为触发器时候,在C# 独立工作模式下,说可以支持使用 ServiceBusReceivedMessage 类型作为触发消息的参数类型:
[Function(nameof(ServiceBusReceivedMessageFunction))] [ServiceBusOutput("outputQueue", Connection = "ServiceBusConnection")] public string ServiceBusReceivedMessageFunction( [ServiceBusTrigger("queue", Connection = "ServiceBusConnection")] ServiceBusReceivedMessage message) { _logger.LogInformation("Message ID: {id}", message.MessageId); _logger.LogInformation("Message Body: {body}", message.Body); _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType); var outputMessage = $"Output message created at {DateTime.Now}"; return outputMessage; }
但是在实际的测试中,却报错:
Cannot convert input parameter 'message' to type 'Azure.Messaging.ServiceBus.ServiceBusReceivedMessage' from type 'System.String'.
Error:System.NotSupportedException:
Deserialization of types without a parameterless constructor, a singular parameterized constructor, or a parameterized constructor annotated with 'JsonConstructorAttribute' is not supported.
Type 'Azure.Messaging.ServiceBus.ServiceBusReceivedMessage'.
Path: $ | LineNumber: 0 | BytePositionInLine: 1.
问题解答
这是 Azure Functions 基础结构的限制而导致的行为。由于ServiceBusReceivedMessage 类型无法反序列化为JSON 类型.
所以,可以使用 [string message] 来代替 [ServiceBusReceivedMessage message].
[Function(nameof(ServiceBusReceivedMessageFunction))] [ServiceBusOutput("outputQueue", Connection = "ServiceBusConnection")] public string ServiceBusReceivedMessageFunction( [ServiceBusTrigger("queue", Connection = "ServiceBusConnection")] string message) { _logger.LogInformation("Message Body: {body}", message); var outputMessage = $"Output message created at {DateTime.Now}"; return outputMessage; }
参考资料
Azure Functions 的 Azure 服务总线触发器 : https://docs.azure.cn/zh-cn/azure-functions/functions-bindings-service-bus-trigger?tabs=python-v2%2Cisolated-process%2Cnodejs-v4%2Cextensionv5&pivots=programming-language-csharp#usage
ServiceBusMessageActions raises grpc exception after migrating to Isolated worker in net8.0 in servicebus trigger execution #2761 : https://github.com/Azure/azure-functions-dotnet-worker/issues/2761
当在复杂的环境中面临问题,格物之道需:浊而静之徐清,安以动之徐生。 云中,恰是如此!