我想通过 Azure 服务总线从 .NET Core 控制台应用程序发送消息,并在 .NET 4.6 控制台应用程序中接收消息。在 .NET Core 中,我为发送方使用 Azure 的新服务总线客户端,该客户端尚未用于生产(根据其自述文件)。
https://github.com/Azure/azure-service-bus-dotnet
我可以使用示例轻松地从 .NET Core 发送并使用 .NET Core 接收。但是,当 .NET 4.6 应用程序订阅该主题并收到相同的消息时,.NET 4.6 应用程序会抛出此异常:
Microsoft.Azure.WebJobs.Host.FunctionInvocationException:
Exception while executing function: Functions.ProcessEvent
System.InvalidOperationException: Exception binding parameter 'message'
The BrokeredMessage with ContentType 'string' failed to
deserialize to a string with the message:
'Expecting element 'string' from namespace
'http://schemas.microsoft.com/2003/10/Serialization/'..
Encountered 'Element' with name 'base64Binary', namespace
http://schemas.microsoft.com/2003/10/Serialization/'. ' --->
System.Runtime.Serialization.SerializationException: Expecting element
'string' from namespace
http://schemas.microsoft.com/2003/10/Serialization/'.. Encountered 'Element'
with name 'base64Binary', namespace
'http://schemas.microsoft.com/2003/10/Serialization/'.
System.Runtime.Serialization.DataContractSerializer.InternalReadObject
(XmlReaderDelegator xmlReader, Boolean verifyObjectName,
DataContractResolver dataContractResolver) at
System.Runtime.Serialization.XmlObjectSerializer.
ReadObjectHandleExceptions(XmlReaderDelegator reader,
Boolean verifyObjectName, DataContractResolver dataContractResolver)
我的 .NET Core 发送器代码是:
using Microsoft.Azure.ServiceBus;
var topicClient = new TopicClient(ServiceBusConnectionString, "topic1");
var msg = new Message(Encoding.UTF8.GetBytes("Hello world"));
topicClient.SendAsync(msg).Wait();
我的 .NET 4.6 接收器代码是:
using Microsoft.Azure.WebJobs;
static void Main()
{
var config = new JobHostConfiguration();
config.UseTimers();
config.UseServiceBus();
var host = new JobHost(config);
host.RunAndBlock();
}
public void ProcessEvent([ServiceBusTrigger("topic1", "the-same-endpoint-as-connection-string")] string message, TextWriter logger)
{
Console.Writeline(message);
}
请注意,我无法更改接收器,因为它是旧系统。
最佳答案
我猜问题是因为 .NET Core 正在将序列化为 JSON 的消息发布到主题,但 NET 4.6 代码尝试使用 DataContract Serializer 来反序列化订阅中的该消息。 (XML?),据我所知,这是完整 .Net 框架库的默认反序列化方法。
如果是这种情况并且您无法修改接收代码,则需要在 .Net Core 上使用 DataContractSerializer
来序列化消息:
var ser = new System.Runtime.Serialization.DataContractSerializer(typeof(string));
var ms = new MemoryStream();
ser.WriteObject(ms, "hello world");
var msg = new Message(ms.ToArray());
您需要 nuget 包System.Runtime.Serialization.Xml
关于c# - 在 Azure ServiceBus 上从 .NET Core 发送方向 .NET 4.6 处理程序发送消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45067209/