How can I convert an XML file to an instance of a MessageContract class?
I'm attempting to test a [MessageContract]
class against an existing sample message, and I'm looking for a way to simplify development by reading the sample message file into an instance of my [MessageContract]
class and seeing how it worked out (I'm dealing with a particularly complex contract here, of non-WCF origin).
My [MessageContract]
class looks something like this:
[MessageContract(IsWrapped = true, WrapperName = "wrapper", WrapperNamespace = "somens")]
public class RequestMessage
{
[MessageHeader(Name = "HeaderElem", Namespace = "otherns")]
public XElement CorrelationTimeToLive { get; set; }
[MessageBodyMember(Name = "id",开发者_开发百科 Namespace = "somens")]
public XElement id { get; set; }
}
I can read the file into an instance of the Message
class, using code such as the following:
var xr = XmlReader.Create("sample_message.xml");
var msg = Message.CreateMessage(xr, int.MaxValue, MessageVersion.Soap12);
That's not particulary helpful, however, because it doesn't allow me to test my [MessageContract]
class at all.
Somewhere in the guts of WCF is a system for turning this Message
instance into an instance of a particular [MessageContract]
class, but what is it?
I just learned how to do this the other day following a talk with a collegue. I think this is what you were asking to do.
namespace MessageContractTest
{
class Program
{
static void Main(string[] args)
{
string action = null;
XmlReader bodyReader = XmlReader.Create(new StringReader("<Example xmlns=\"http://tempuri.org/\"><Gold>109</Gold><Message>StackOverflow</Message></Example>"));
Message msg = Message.CreateMessage(MessageVersion.Default, action, bodyReader);
TypedMessageConverter converter = TypedMessageConverter.Create(typeof(Example), "http://tempuri.org/IFoo/BarOperation");
Example example = (Example)converter.FromMessage(msg);
}
}
[MessageContract]
public class Example
{
[MessageHeader]
public string Hello;
[MessageHeader]
public double Value;
[MessageBodyMember]
public int Gold;
[MessageBodyMember]
public string Message;
}
}
You will need to deserialize the XML into an instance of your data contract. This is what WCF is doing for you under the covers.
Here is a quick tutorial that will show you how to invoke the DataContractSerializer
manually for your XML.
精彩评论