我需要编写一个测试,我手动创建一个Microsoft.Azure.ServiceBus.Message并将其序列化为JSON。示例代码:
var message = new Microsoft.Azure.ServiceBus.Message
{
MessageId = "0c8dfad9-6f0f-4d7f-a248-2a48fc899486",
CorrelationId = "78b507b0-6266-458d-afe6-7882c935e481",
Body = Encoding.UTF8.GetBytes("Hello world"),
};
var json = JsonConvert.SerializeObject(message);
但是,序列化时出现以下异常:
Newtonsoft.Json.JsonSerializationException :
Error getting value from 'ExpiresAtUtc' on 'Microsoft.Azure.ServiceBus.Message'.
---- System.InvalidOperationException : Operation is not valid due to the current state of the object.
如何创建有效消息(可以在以后序列化)的任何想法? ExpiresAtUtc只是因此无法直接设置。有没有办法间接设置它?
答案 0 :(得分:2)
ExpiresAtUtc
由代理设置,被视为内部(SystemProperties
集合),并且是有意设计的。关于测试有一个similar question,如果你真的需要这个,那么实现它的唯一方法就是使用反射。
var message = new Message();
//message.TimeToLive = TimeSpan.FromSeconds(10);
var systemProperties = new Message.SystemPropertiesCollection();
// systemProperties.EnqueuedTimeUtc = DateTime.UtcNow.AddMinutes(1);
var bindings = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.SetProperty;
var value = DateTime.UtcNow.AddMinutes(1);
systemProperties.GetType().InvokeMember("EnqueuedTimeUtc", bindings, Type.DefaultBinder, systemProperties, new object[] { value});
// workaround "ThrowIfNotReceived" by setting "SequenceNumber" value
systemProperties.GetType().InvokeMember("SequenceNumber", bindings, Type.DefaultBinder, systemProperties, new object[] { 1 });
// message.systemProperties = systemProperties;
bindings = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.SetProperty;
message.GetType().InvokeMember("SystemProperties", bindings,Type.DefaultBinder, message, new object[] { systemProperties });
注意这种方法不是来自Azure Service Bus团队,因为他们认为这可能会导致您的生产过程中出现危险的做法。