CreateBufferedCopy会在末尾离开流位置吗?

时间:2012-06-26 15:48:39

标签: c# wcf idispatchmessageinspector

AfterReceiveRequest方法中,如果我这样做:

MessageBuffer buffer = request.CreateBufferedCopy(int.MaxValue);
Message requestCopy = buffer.CreateMessage();

//handle message stuff here

request = newMessage;
buffer.Close();

以上是否将流的位置保留在最后?基本上我要问的是,在再次阅读请求时,创建缓冲副本会导致任何问题吗?

这就是我到达这种情况的方式,在消息检查器中,我最初没有创建缓冲副本,但后来我遇到了错误消息,在向服务发送请求之后已经读取了请求在线研究,我发现我需要创建一个消息副本,我只是想确保这不会导致任何位置或其他任何问题?

我想通过创建一个要在消息检查器中使用的副本,我没有读取消息两次,复制被读取一次用于记录,当它被分配给ref参数时,我打电话时使用了一个对服务,对吗?

2 个答案:

答案 0 :(得分:0)

为了多次重用消息,您必须为其创建内存副本。为此,使用消息对象实例的CreateBufferCopy。调用此方法不会改变消息的状态。

  

以上是否将流的位置保留在最后?   不适用于此类流。

答案 1 :(得分:0)

以下是我在项目中使用它的方法。它显示了如何在BeforeSendReply方法中正确复制消息。不是您要使用的方法,但应使用相同的代码:

    public void BeforeSendReply(ref Message reply, object correlationState)
    {
        var properties = reply.Properties;
        var contextKey = GetContextKey(properties);
        bool statusCodeFound = false;
        var statusCode = HttpStatusCode.OK;
        if (properties.Keys.Contains("httpResponse"))
        {
            statusCode = ((System.ServiceModel.Channels.HttpResponseMessageProperty)properties["httpResponse"]).StatusCode;
            statusCodeFound = true;
        }
        var buffer = reply.CreateBufferedCopy(int.MaxValue);

        //Must use a buffer rather than the origonal message, because the Message's body can be processed only once.
        Message msg = buffer.CreateMessage();

        //Setup StringWriter to use as input for our StreamWriter
        //This is needed in order to capture the body of the message, because the body is streamed.
        StringWriter stringWriter = new StringWriter();
        XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter);
        msg.WriteMessage(xmlTextWriter);
        xmlTextWriter.Flush();
        xmlTextWriter.Close();

        var returnValue = stringWriter.ToString();

        // I do my logging of the "returnValue" variable here. You can do whatever you want.

        //Return copy of origonal message with unaltered State
        reply = buffer.CreateMessage();
    }