You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Azure Function ServiceBus无application_properties属性报错求助

问题根因

核心问题1:混淆了两个不同ServiceBusMessage类的属性定义

  • Azure Function触发器注入的入参类型为 func.ServiceBusMessage,它的自定义属性字段固定为 user_properties,和Service Bus SDK的版本无关
  • 你通过azure.servicebus包新建的待发送消息类型为 ServiceBusMessage,5.x+版本的自定义属性字段为 application_properties,且支持直接传入字符串类型的键值,不需要转bytes

核心问题2:错误的从序列化字符串中取属性

你更新后的代码里把result定义为json.dumps()返回的字符串对象,字符串本身没有user_properties属性,你需要的入参属性直接从触发器入参message中读取即可

核心问题3:多余的ServiceBusClient实例化

你已经调用ServiceBusClient.from_connection_string实例化了客户端,后续不需要再次调用该方法重复实例化

修正后的可运行代码
import logging
import json

import azure.functions as func
from azure.servicebus import ServiceBusClient, ServiceBusMessage


def main(message: func.ServiceBusMessage):
    message_content_type = message.content_type
    message_body = message.get_body().decode("utf-8")
    
    # 序列化消息内容
    result = json.dumps({
        'message_id': message.message_id,
        'body': message_body,
        'content_type': message_content_type,
        'user_properties': message.user_properties,
        'metadata' : message.metadata
    })
    logging.info(result)

    CONN_STR = "XXX"
    topic_b = "topic_b"

    def send_output(sender):
        message_out = ServiceBusMessage(
            result,
            content_type="application/json",
            # 直接从触发器入参message中取属性,使用SDK要求的application_properties字段
            application_properties={
                # 示例1:透传原消息的source自定义属性
                'source': message.user_properties.get('source', 'default_source'),
                # 示例2:写入原消息的message_id
                'tenant': message.message_id
            }
        )
        sender.send_messages(message_out)

    # 仅实例化一次ServiceBusClient
    with ServiceBusClient.from_connection_string(conn_str=CONN_STR, logging_enable=True) as servicebus_client:
        with servicebus_client.get_topic_sender(topic_name=topic_b) as sender:
            send_output(sender)
注意事项
  • 如果你要透传原消息的所有自定义属性,直接赋值application_properties=message.user_properties即可
  • application_properties的键值不要传入bytes类型,直接用字符串即可,SDK会自动处理编码
  • 不需要尝试从sender或者序列化后的消息字符串中读取自定义属性,所有入参的元数据都可以直接从触发器的message入参获取

内容的提问来源于stack exchange,提问作者Nayden Van

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 16:15:05