c# - WCF : This message cannot support the operation because it has been copied

标签 c# wcf

private static string ReadDefaultMessageBody(ref Message message)
{
    const string XmlReaderName = "binary";

    if (message.IsEmpty)
    {
        return string.Empty;
    }

    MessageBuffer buffer = message.CreateBufferedCopy(int.MaxValue);
    try
    {
        // Copy the original message and use it for reading.
        Message messageCopy = buffer.CreateMessage();

        // Re-create original message  
        message = buffer.CreateMessage();

        // Dump payload from original message  
        // It is in either plain text or in base64 encoded string  
        using (var reader = messageCopy.GetReaderAtBodyContents())
        {
            return string.Compare(reader.Name, XmlReaderName, StringComparison.OrdinalIgnoreCase) == 0
                            ? Encoding.Default.GetString(Convert.FromBase64String(reader.ReadInnerXml()))
                            : reader.ReadOuterXml();
        }                
    }
    finally
    {
        buffer.Close();
    }
}

我在 stackoverflow 上引用了一些链接:This message cannot support the operation because it has been copied

MessageInspector message: "This message cannot support the operation because it has been copied."

从第一个链接来看,消息似乎不能被复制多次。从第二个链接来看,如果我们重新创建消息,消息似乎可以被复制不止一次。

有人可以指出我正在做的错误吗?由于此方法被多次调用并且出现以下错误:“此消息无法支持该操作,因为它已被复制”

异常:System.InvalidOperationException:此消息无法支持该操作,因为它已被复制。\r\n 在 System.ServiceModel.Channels.Message.CreateBufferedCopy(Int32 maxBufferSize)

最佳答案

试试这段代码:

MessageBuffer buffer = message.CreateBufferedCopy(Int32.MaxValue);
    message = buffer.CreateMessage();

    var copy = buffer.CreateMessage();

如原文所述answer

The message variable is passed into your code by reference and contains the message WCF will work with. It cannot be in a "already read" state to be valid for WCF use. You can, however, call buffer.CreateMessage() multiple times to create clones of the actual message WCF is working with. If you want to inject something into the existing message, you can create a new message from the old message and pass the modified message back to WCF

关于c# - WCF : This message cannot support the operation because it has been copied,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34189274/

相关文章:

wcf - 如何将流与返回大型数据集的 WCF 服务结合使用?

c# - 在 .NET 中序列化对象时省略所有 xsi 和 xsd 命名空间?

c# - 对 Windows.Forms 的十六进制查看器控件的建议?

c# - 在 NancyFx 中向响应添加位置 header 的正确方法

php 使用 WCF SSL SOAP 客户端 1.2

wcf - 将 System.Exception 对象作为参数传递给 WCF Service 方法

c# - 初始化 ThreadStatic 字段仍然导致 NullReferenceException

c# - 在 MVVM WPF 应用程序中打开新窗口

c# - 如何将 WCF 服务的引用添加到 .Net CF 2.0 应用程序?

c# - 在没有 OperationContext 的情况下创建可测试的 WCF 服务