Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/wcf/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Can';无法使IClientMessageFormatter正常工作_C#_Wcf - Fatal编程技术网

C# Can';无法使IClientMessageFormatter正常工作

C# Can';无法使IClientMessageFormatter正常工作,c#,wcf,C#,Wcf,我有一个自定义IClientMessageFormatter,它当前向消息中指定的xml元素添加属性: public class GetOrdersMessageFormatter : IClientMessageFormatter { readonly IClientMessageFormatter original; public GetOrdersMessageFormatter(IClientMessageFormatter actual) {

我有一个自定义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:用于消息正文的XmlReader必须位于元素上。 参数名称:reader

服务器堆栈跟踪: 位于System.ServiceModel.Channel.XmlReaderBodyWriter.OnWriteBodyContents(XmlDictionaryWriter编写器) 位于System.ServiceModel.Channel.BodyWriter.WriteByContents(XmlDictionaryWriter编写器) 位于System.ServiceModel.Channel.BodyWriterMessage.OnWriteByContents(XmlDictionaryWriter编写器) 位于System.ServiceModel.Channel.Message.OnWriteMessage(XmlDictionaryWriter编写器) 位于System.ServiceModel.Channel.Message.WriteMessage(XmlDictionaryWriter编写器) 位于System.ServiceModel.Channels.BufferedMessageWriter.WriteMessage(消息消息,BufferManager BufferManager,Int32 initialOffset,Int32 maxSizeQuota) 位于System.ServiceModel.Channels.TextMessageEncoderFactory.TextMessageEncoder.WriteMessage(消息消息,Int32 maxMessageSize,BufferManager BufferManager,Int32 messageOffset) 在System.ServiceModel.Channels.HttpOutput.SerializedBufferedMessage(消息消息)处 位于System.ServiceModel.Channels.HttpOutput.Send(TimeSpan超时) 位于System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.SendRequest(消息消息,TimeSpan超时) 位于System.ServiceModel.Channels.RequestChannel.Request(消息消息,TimeSpan超时) 位于System.ServiceModel.Dispatcher.RequestChannelBinder.Request(消息消息,TimeSpan超时) 在System.ServiceModel.Channels.ServiceChannel.Call(字符串操作、布尔单向、ProxyOperationRuntime操作、对象[]输入、对象[]输出、时间跨度超时) 位于System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage方法调用,ProxyOperationRuntime操作) 位于System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage消息)

我想,这可能是我需要使用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();
    }
}
公共类StackOverflow_8669406
{
公共类GetOrdersMessageFormatter:IClientMessageFormatter
{
只读IClientMessageFormatter原件;
公共GetOrdersMessageFormatter(IClientMessageFormatter实际)
{
原始=实际;
}
public void AddArrayNamespace(XmlNode节点)
{
如果(节点!=null)
{
var attribute=node.OwnerDocument.CreateAttribute(“测试”);
attribute.Value=“测试”;
node.Attributes.Append(属性);
}
}
公共对象反序列化reply(消息,对象[]参数)
{
返回original.DeserializeReply(消息、参数);
}
公共消息序列化请求(MessageVersion MessageVersion,对象[]参数)
{
消息newMessage=null;
var message=original.SerializeRequest(messageVersion,参数);
if(message.Headers.Action==“urn:Mage\u Api\u Model\u Server\u HandlerAction”)
{
var doc=新的XmlDocument();
使用(var reader=message.GetReaderAtBodyContents())
{
文件加载(读卡器);
}
如果(doc.DocumentElement!=null)
{
开关(doc.DocumentElement.LocalName)
{
案例“呼叫”:
AddArrayNamespace(doc.SelectSingleNode(//args));
打破
}
}
var ms=新内存流();
XmlWriterSettings ws=新的XmlWriterSettings
{
CloseOutput=false,
};
使用(var xw=XmlWriter.Create(ms,ws))
{
单据保存(xw);
xw.Flush();
}
Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray());
ms.Position=0;
var xr=XmlReader.Create(毫秒);
newMessage=Message.CreateMessage(Message.Version,null,xr);
newMessage.Headers.CopyHeadersFrom(消息);
newMessage.Properties.CopyProperties(message.Properties);
}
返回新消息;
}
}
[ServiceContract(名称空间=”)]
公共接口测试
{
[操作合同(Action=“urn:Mage\u Api\u Model\u Server\u HandlerAction”)]
int调用(字符串参数);
}
公共类服务:ITest
{
公共int调用(字符串参数)
{
返回int.Parse(args);
}
}
类MyBehavior:IOperationBehavior
{
public void AddBindingParameters(OperationDescription OperationDescription,BindingParameterCollection bindingParameters)
{
}
public void ApplyClientBehavior(操作说明操作说明,客户端操作客户端操作)
{
clientOperation.Formatter=新的GetOrdersMessageFormatter(clientOperation.Formatter);
}
public void ApplyDispatchBehavior(操作说明操作说明,调度操作调度操作)
{
}
公共无效验证(OperationDescription OperationDescription)
{
}