使用C#编写Azure函数向队列添加消息遇异常问题
Let's tackle your two questions about Azure Functions and Service Bus queues step by step:
ICollector<string> feasible, and if so, what's causing the missing messages? Absolutely, ICollector<string> is a valid and straightforward way to send string messages to a Service Bus queue via Azure Functions bindings. If your local run shows no errors but messages aren't appearing in the queue, here are the most likely issues to check:
- Incorrect connection string: Double-check your
local.settings.jsonfile to ensure theAzureWebJobsServiceBussetting uses the correct connection string for your Service Bus namespace. Make sure the connection hasSendorManagepermissions enabled for the queue. - Function execution failure:
ICollectorbatches messages and only commits them to the queue when the function completes successfully. If your code throws an unhandled exception after callingqueue.Add(msg), or returns early before finishing execution, the messages won't be sent. Add logging likelog.Info($"Added message to collector: {msg}")to confirm theAddmethod runs, and verify the rest of your function logic works without issues. - Queue name mismatch: Ensure the queue name in your binding (
[Queue("myqueuename")]) exactly matches the name of the queue in your Service Bus namespace—names are case-sensitive!
BrokeredMessage) suitable for this scenario? No, the legacy WindowsAzure.ServiceBus (v1.1) package and its BrokeredMessage class are not compatible with Azure Functions' modern Service Bus bindings. Here's why:
Azure Functions uses the newer Microsoft.Azure.ServiceBus SDK under the hood for its Service Bus integrations. The two SDKs are completely separate and don't share compatible types—passing a BrokeredMessage from v1.1 to an ICollector<string> causes serialization errors (like the "unable to read DeliveryCount" problem you encountered) because the binding expects a string, not a legacy message object.
If you need to send a custom object (like your test class), use one of these compatible approaches instead:
- Use
ICollector<test>directly as your function parameter. The Functions runtime will automatically serialize the object to JSON and send it as a queue message. - Manually serialize your object to a string (e.g., with
JsonConvert.SerializeObject()from Newtonsoft.Json) and send that string viaICollector<string>.
内容的提问来源于stack exchange,提问作者Paul Michaels

