【发布时间】:2021-11-07 22:29:30
【问题描述】:
我正在尝试将字符串值添加到 RabbitMQ 消息中。
当我在此处撰写消息时,代码如下:
IBasicProperties props = channel.CreateBasicProperties();
props.ContentType = "text/plain";
props.DeliveryMode = 2;
props.Expiration = "36000000";
props.Headers = new Dictionary<string, object>();
props.Headers.Add("entityId", id);
props.Headers.Add("type", GetMessageType(id));
channel.BasicPublish(exchange: "messages",
routingKey: "",
basicProperties: props,
body: body);
方法GetMessageType返回一个字符串。
我这样检索消息:
private void ConsumerOnReceived(object sender, BasicDeliverEventArgs e)
{
var firstMessage = "PO Received";
var secondMessage = "Do you want to print a Back Order Fill Report?";
var id = (int) e.BasicProperties.Headers.FirstOrDefault(x => x.Key == "entityId").Value;
string type;
try
{
type = (string)e.BasicProperties.Headers.FirstOrDefault(x => x.Key == "type").Value;
}
catch (Exception exception)
{
Console.WriteLine(exception);
throw;
}
if (type == "OrderCreated")
{
firstMessage = "Sales Order Created";
secondMessage = "Do you want to print the Order?";
}
...
第一个标头值 (entityId) 可以正常检索。第二个(类型)导致异常。
异常消息:Message = "Unable to cast object of type 'System.Byte[]' to type 'System.String'."
我需要将字节数组转换回字符串吗?还是应该只传递整数?
如果我需要将字节数组转换回字符串,我该怎么做?
【问题讨论】: