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