C# 仅获取 WCf 消息的正文

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1708591/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 20:09:21  来源:igfitidea点击:

Get Just the Body of a WCf Message

c#xmlwcfsoap

提问by Jon

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.

我有一个接受 ac# Message 类型的服务方法,我只想提取该soap消息的正文并使用它来构造一个全新的消息。我不能GetBody<>()在 Message 类上使用该方法,因为我不知道将正文序列化为什么类型。

Does any one know 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?

有谁知道如何从消息中提取正文?或者构造一个具有相同正文的新消息,即没有原始消息头等?

采纳答案by Ray Vernagus

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. =)

不是抢占 Yann 的答案,而是为了它的价值,这里有一个完整的示例,将消息正文复制到具有不同操作标头的新消息中。您也可以添加或自定义其他标题作为示例的一部分。我花了太多时间写这篇文章,只是把它扔掉。=)

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

回答by Yann Schwartz

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...                
}