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/

相关文章:

c# - Entity Framework 自动预加载

c# - 当不需要 WCF DataMember 时

c# - "On Exit"用于控制台应用程序

c# - WPF DragDropEffects 在 Drop 事件中未正确设置

c# - 命名空间中不存在Visual Studio,但添加了引用

rest - WCF、Web API、WCF REST 和 Web 服务之间的区别?

c# - Linq 表达式树 Any() 问题

c# - 创建登录表单

wcf - ELMAH 的错误日志记录在带有 basicHttpBinding 的 IIS 中托管的 WCF 服务中不起作用

wcf - 在 WCF 中命名通用 DataContract