1

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

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

//handle message stuff here

request = newMessage;
buffer.Close();

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

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

我想通过创建要在消息检查器中使用的副本,我不会两次阅读该消息,该副本被读取一次以进行日志记录,当它被分配给 ref 参数时,当我调用该服务时使用该副本, 正确的?

4

2 回答 2

0

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

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

于 2012-06-27T19:24:52.987 回答
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();
    }
于 2013-05-09T14:31:29.713 回答