使用MessageQueue.GetAllMessages读取私有MSMQ报错,求解决方案
解决MSMQ读取消息时“找不到可读取此消息的格式化器”异常
出现这个异常的核心原因是:读取消息时使用的格式化器,和发送该消息时用的格式化器不匹配,导致无法反序列化消息体。以下是针对性的解决办法:
1. 匹配发送端使用的格式化器
根据消息发送时的格式化类型,在读取代码中指定对应的格式化器:
若发送端用XmlMessageFormatter(.NET常见场景)
如果消息体是字符串或自定义实体类,需要明确指定要反序列化的类型:
string queuePath = @".\private$\test"; MessageQueue queue = new MessageQueue(queuePath); // 替换为实际消息体的类型,多个类型用逗号分隔 queue.Formatter = new XmlMessageFormatter(new Type[] { typeof(string), typeof(YourCustomEntity) }); Message[] messages = queue.GetAllMessages(); foreach (Message msg in messages) { Console.WriteLine(msg.Body); }
注意:自定义实体类YourCustomEntity必须和发送端的类结构、命名空间完全一致
若发送端用BinaryMessageFormatter
直接设置对应的二进制格式化器即可:
queue.Formatter = new BinaryMessageFormatter();
若消息来自非.NET系统或手动通过MSMQ工具发送
这类场景通常用ActiveX格式化器,设置如下:
queue.Formatter = new ActiveXMessageFormatter();
2. 先确认消息的格式化器类型
如果不确定发送端用的哪种格式化器,可以先打印消息的FormatterName属性来排查:
string queuePath = @".\private$\test"; MessageQueue queue = new MessageQueue(queuePath); Message[] messages = queue.GetAllMessages(); foreach (Message msg in messages) { // 输出格式化器名称,根据结果选择对应格式化器 Console.WriteLine(msg.FormatterName); }
内容的提问来源于stack exchange,提问作者Vipul Garg
相关产品推荐
相关产品推荐

