用azure brokeredmessage得到身体而不知道类型

时间:2013-03-15 20:49:34

标签: c# azure azureservicebus

在Azure Service Bus中使用代理消息时,可以使用调用.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>();

3 个答案:

答案 0 :(得分:70)

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

Stream stream = message.GetBody<Stream>();
StreamReader reader = new StreamReader(stream);
string s = reader.ReadToEnd();

答案 1 :(得分:32)

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

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;
}

答案 2 :(得分:5)

在ContentType用于检测体型之前的样本中。我相信ContentType应该由发件人设置。 我做类似的逻辑,我将一个消息属性设置为发送方的对象类型,并在接收方调用GetBody&lt;&gt;(),其类型从message属性中恢复。 像这样:

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();
                    }
                }