开发者

Get Just the Body of a WCf Message

开发者 https://www.devze.com 2022-12-11 14:12 出处:网络
I\'m having a bit of trouble with what should be a simple problem. I have a service method that takes in a c# Message type and i want to just extract the body of that soap message and use it to const

I'm having a bit of trouble with what should be a simple problem.

I have a service method that takes in a c# Message type and i want to just extract the body of that soap message and use it to construct a completely new message. I can't use the GetBody<>() method on the Message class as i would not know what type to serialise the body into.

Does any one kn开发者_C百科ow how to just extract the body from the message? Or construct a new message which has the same body i.e. without the orginal messages header etc?


You can access the body of the message by using the GetReaderAtBodyContents method on the Message:

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. 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();
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消