35

在 Azure 服务总线中使用代理消息时,可以通过调用 .GetBody 检索消息正文。代码很简单:

var msg = subscription.Receive();
MyPayload payload = msg.GetBody<MyPayload>();

但是,有没有办法在不明确知道 body 对象的类的情况下检索 Body?

var msg = subscription.Receive();
Type bodyType = Type.GetType( msg.ContentType);

var payload = msg.GetBody<bodyType>();
4

3 回答 3

80

如果意图是只获取消息正文而不考虑内容,则可以将其作为流获取。

Stream stream = message.GetBody<Stream>();
StreamReader reader = new StreamReader(stream);
string s = reader.ReadToEnd();
于 2013-03-15T21:05:21.517 回答
31

以下是从 brokeredmessage 反序列化的完整代码:

public T GetBody<T>(BrokeredMessage brokeredMessage)
{
  var ct = brokeredMessage.ContentType;
  Type bodyType = Type.GetType(ct, true);

  var stream = brokeredMessage.GetBody<Stream>();
  DataContractSerializer serializer = new DataContractSerializer(bodyType);
  XmlDictionaryReader reader = XmlDictionaryReader.CreateBinaryReader(stream, XmlDictionaryReaderQuotas.Max);
  object deserializedBody = serializer.ReadObject(reader);
  T msgBase = (T)deserializedBody;
  return msgBase;
}
于 2013-03-27T16:44:59.780 回答
6

在 ContentType 之前的示例中用于检测正文类型。我相信 ContentType 应该由发件人设置。我做了类似的逻辑,我将消息属性之一设置为发送方的对象类型,并在接收方上调用 GetBody<>(),类型从消息属性中检索。像这样:

public void SendData(object payloadData)
    {
        if (payloadData == null) return;

        var queueClient = QueueClient.CreateFromConnectionString(ConnectionString, _queueName);

        var brokeredMessage = new BrokeredMessage(payloadData);
        brokeredMessage.Properties["messageType"] = payloadData.GetType().AssemblyQualifiedName;
        queueClient.Send(brokeredMessage);
    }

消息属性“messageType”具有类型的全名。

在接收方,我这样做:

 var messageBodyType = Type.GetType(receivedMessage.Properties["messageType"].ToString());
                if (messageBodyType == null)
                {
                    //Should never get here as a messagebodytype should
                    //always be set BEFORE putting the message on the queue
                    Trace.TraceError("Message does not have a messagebodytype" +
                                     " specified, message {0}", receivedMessage.MessageId);
                    receivedMessage.DeadLetter();
                }


                //read body only if event handler hooked
                    var method = typeof(BrokeredMessage).GetMethod("GetBody", new Type[] { });
                    var generic = method.MakeGenericMethod(messageBodyType);
                    try
                    {
                        var messageBody = generic.Invoke(receivedMessage, null);
                         DoSomethingWithYourData();
                        receivedMessage.Complete();
                    }
                    catch (Exception e)
                    {
                        Debug.Write("Can not handle message. Abandoning.");
                        receivedMessage.Abandon();
                    }
                }
于 2013-11-11T18:58:53.117 回答