Whenever object of a class marked with MessageContract attribute is serialized, I see that it开发者_如何学Go looks for [MessageBodyMember] members and serializes them under seperate XML elements in the message. Is there anyway to directly serialize them, skipping the wrapper node ?
Eg.
[System.ServiceModel.MessageContractAttribute(IsWrapped = false)]
Class A
{
[MessageBodyMember]
public string MyMessage
{
get;
set;
}
}
When this gets serialized it becomes
<Body>
<MyMessage>....</MyMessage>
</Body>
but i want it to become
<Body>
....
</Body>
I know this might be illogical. Any suggestions ?
This should do it:-
[MessageBodyMember(Name="Body")]
If I understand your question correctly, you want to remove the <MyMessage>
element and have the string itself on the message body. Well, the message contract won't work for you. You can remove the outer wrapper for the message contract, but not the wrappers for individual members.
What you can do, is to create a Message
object based on a BodyWriter
instance you create, and this body writer can write the output XML in whatever form it wants to. See the code below for an example.
public class StackOverflow_7010654
{
[MessageContract(IsWrapped = false)]
public class MyMC
{
[MessageBodyMember]
public string MyMessage { get; set; }
}
public static void Test()
{
TypedMessageConverter tmc = TypedMessageConverter.Create(typeof(MyMC), "Action");
Message msg = tmc.ToMessage(new MyMC { MyMessage = "some string" }, MessageVersion.Soap11);
Console.WriteLine(msg); // message with the <MyMessage> element
Console.WriteLine();
msg = Message.CreateMessage(MessageVersion.Soap11, "Action", new MyBodyWriter());
Console.WriteLine(msg); // message without the <MyMessage> element
}
public class MyBodyWriter : BodyWriter
{
public MyBodyWriter() : base(true) { }
protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
{
writer.WriteString("some string");
}
}
}
精彩评论