简体   繁体   English

获得WCF消息的正文

[英]Get Just the Body of a WCf Message

I'm having a bit of trouble with what should be a simple problem. 我应该在一个简单的问题上遇到一些麻烦。

I have a service method that takes in ac# Message type and i want to just extract the body of that soap message and use it to construct a completely new message. 我有一个服务方法,它采用ac#Message类型,我想只是提取该soap消息的主体并使用它来构造一个全新的消息。 I can't use the GetBody<>() method on the Message class as i would not know what type to serialise the body into. 我不能在Message类上使用GetBody<>()方法,因为我不知道序列化主体的类型。

Does any one know how to just extract the body from the message? 有没有人知道如何从消息中提取身体? Or construct a new message which has the same body ie without the orginal messages header etc? 或者构造一个具有相同主体的新消息,即没有原始消息头等?

You can access the body of the message by using the GetReaderAtBodyContents method on the Message: 您可以使用Message上的GetReaderAtBodyContents方法访问消息正文:

using (XmlDictionaryReader reader = message.GetReaderAtBodyContents())
{
     string content = reader.ReadOuterXml();
     //Other stuff here...                
}

Not to preempt Yann's answer, but for what it's worth, here's a full example of copying a message body into a new message with a different action header. 不是为了取代Yann的答案,而是为了它的价值,这是一个将消息体复制到具有不同动作头的新消息的完整示例。 You could add or customize other headers as a part of the example as well. 您也可以添加或自定义其他标头作为示例的一部分。 I spent too much time writing this up to just throw it away. 我花了太多时间写这篇文章把它扔掉。 =) =)

class Program
{
    [DataContract]
    public class Person
    {
        [DataMember]
        public string FirstName { get; set; }

        [DataMember]
        public string LastName { get; set; }

        public override string ToString()
        {
            return string.Format("{0}, {1}", LastName, FirstName);
        }
    }

    static void Main(string[] args)
    {
        var person = new Person { FirstName = "Joe", LastName = "Schmo" };
        var message = System.ServiceModel.Channels.Message.CreateMessage(MessageVersion.Default, "action", person);

        var reader = message.GetReaderAtBodyContents();
        var newMessage = System.ServiceModel.Channels.Message.CreateMessage(MessageVersion.Default, "newAction", reader);

        Console.WriteLine(message);
        Console.WriteLine();
        Console.WriteLine(newMessage);
        Console.WriteLine();
        Console.WriteLine(newMessage.GetBody<Person>());
        Console.ReadLine();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM