gpt4 book ai didi

c# - 无法让 IClientMessageFormatter 工作

转载 作者:行者123 更新时间:2023-12-05 02:24:48 29 4
gpt4 key购买 nike

我有自定义 IClientMessageFormatter,它当前将属性添加到消息中指定的 xml 元素:

public class GetOrdersMessageFormatter : IClientMessageFormatter
{
readonly IClientMessageFormatter original;

public GetOrdersMessageFormatter(IClientMessageFormatter actual)
{
original = actual;
}

public void AddArrayNamespace(XmlNode node)
{
if (node != null)
{
var attribute = node.OwnerDocument.CreateAttribute("test");
attribute.Value = "test";
node.Attributes.Append(attribute);
}
}

public object DeserializeReply(Message message, object[] parameters)
{
return original.DeserializeReply(message, parameters);
}

public Message SerializeRequest(MessageVersion messageVersion, object[] parameters)
{
Message newMessage = null;

var message = original.SerializeRequest(messageVersion, parameters);

if (message.Headers.Action == "urn:Mage_Api_Model_Server_HandlerAction")
{
var doc = new XmlDocument();

using (var reader = message.GetReaderAtBodyContents())
{
doc.Load(reader);
}

if (doc.DocumentElement != null)
{
switch (doc.DocumentElement.LocalName)
{
case "call":
AddArrayNamespace(doc.SelectSingleNode("//args"));
break;
}
}

using (var ms = new MemoryStream())
{
using (var xw = XmlWriter.Create(ms))
{
doc.Save(xw);

ms.Position = 0;
using (var xr = XmlReader.Create(ms))
{
newMessage = Message.CreateMessage(message.Version, null, xr);
newMessage.Headers.CopyHeadersFrom(message);
newMessage.Properties.CopyProperties(message.Properties);
}
}
}
}

return newMessage;
}
}

它给出异常

System.ArgumentException : The XmlReader used for the body of the message must be positioned on an element. Parameter name: reader

Server stack trace: at System.ServiceModel.Channels.XmlReaderBodyWriter.OnWriteBodyContents(XmlDictionaryWriter writer) at System.ServiceModel.Channels.BodyWriter.WriteBodyContents(XmlDictionaryWriter writer) at System.ServiceModel.Channels.BodyWriterMessage.OnWriteBodyContents(XmlDictionaryWriter writer) at System.ServiceModel.Channels.Message.OnWriteMessage(XmlDictionaryWriter writer) at System.ServiceModel.Channels.Message.WriteMessage(XmlDictionaryWriter writer) at System.ServiceModel.Channels.BufferedMessageWriter.WriteMessage(Message message, BufferManager bufferManager, Int32 initialOffset, Int32 maxSizeQuota) at System.ServiceModel.Channels.TextMessageEncoderFactory.TextMessageEncoder.WriteMessage(Message message, Int32 maxMessageSize, BufferManager bufferManager, Int32 messageOffset) at System.ServiceModel.Channels.HttpOutput.SerializeBufferedMessage(Message message) at System.ServiceModel.Channels.HttpOutput.Send(TimeSpan timeout) at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.SendRequest(Message message, TimeSpan timeout) at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout) at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout) at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout) at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation) at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)

我想,我可能需要使用 message.CreateBufferedCopy() 创建消息副本并使用该副本加载 XmlDocument,但这也没有用。可能有人知道我做错了什么,或者知道示例,它在做几乎相同的事情(我的意思是在发送消息 xml 之前影响它)。

最佳答案

你的格式化程序中的问题是你正在创建一个带有阅读器(和一个流)的消息,这些阅读器在消息被使用之前被处理掉。从流和读取器的创建中删除“using”语句后,请求通过 - 请参见下面的代码。

public class StackOverflow_8669406
{
public class GetOrdersMessageFormatter : IClientMessageFormatter
{
readonly IClientMessageFormatter original;

public GetOrdersMessageFormatter(IClientMessageFormatter actual)
{
original = actual;
}

public void AddArrayNamespace(XmlNode node)
{
if (node != null)
{
var attribute = node.OwnerDocument.CreateAttribute("test");
attribute.Value = "test";
node.Attributes.Append(attribute);
}
}

public object DeserializeReply(Message message, object[] parameters)
{
return original.DeserializeReply(message, parameters);
}

public Message SerializeRequest(MessageVersion messageVersion, object[] parameters)
{
Message newMessage = null;

var message = original.SerializeRequest(messageVersion, parameters);

if (message.Headers.Action == "urn:Mage_Api_Model_Server_HandlerAction")
{
var doc = new XmlDocument();

using (var reader = message.GetReaderAtBodyContents())
{
doc.Load(reader);
}

if (doc.DocumentElement != null)
{
switch (doc.DocumentElement.LocalName)
{
case "call":
AddArrayNamespace(doc.SelectSingleNode("//args"));
break;
}
}

var ms = new MemoryStream();

XmlWriterSettings ws = new XmlWriterSettings
{
CloseOutput = false,
};

using (var xw = XmlWriter.Create(ms, ws))
{
doc.Save(xw);
xw.Flush();
}

Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray()));

ms.Position = 0;
var xr = XmlReader.Create(ms);
newMessage = Message.CreateMessage(message.Version, null, xr);
newMessage.Headers.CopyHeadersFrom(message);
newMessage.Properties.CopyProperties(message.Properties);
}

return newMessage;
}
}

[ServiceContract(Namespace = "")]
public interface ITest
{
[OperationContract(Action = "urn:Mage_Api_Model_Server_HandlerAction")]
int call(string args);
}
public class Service : ITest
{
public int call(string args)
{
return int.Parse(args);
}
}
class MyBehavior : IOperationBehavior
{
public void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters)
{
}

public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)
{
clientOperation.Formatter = new GetOrdersMessageFormatter(clientOperation.Formatter);
}

public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
{
}

public void Validate(OperationDescription operationDescription)
{
}
}
public static void Test()
{
string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
host.AddServiceEndpoint(typeof(ITest), new BasicHttpBinding(), "");
host.Open();
Console.WriteLine("Host opened");

ChannelFactory<ITest> factory = new ChannelFactory<ITest>(new BasicHttpBinding(), new EndpointAddress(baseAddress));
foreach (OperationDescription operation in factory.Endpoint.Contract.Operations)
{
operation.Behaviors.Add(new MyBehavior());
}

ITest proxy = factory.CreateChannel();
Console.WriteLine(proxy.call("4455"));

((IClientChannel)proxy).Close();
factory.Close();

Console.Write("Press ENTER to close the host");
Console.ReadLine();
host.Close();
}
}

关于c# - 无法让 IClientMessageFormatter 工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8669406/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com