最后我把它整理出来,得到了覆盖 Body Writer 类的解决方案。请在下面找到详细的解决方案。
namespace WcfServiceRaw
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
[ServiceContract]
public interface IService1
{
[OperationContract(ReplyAction = "ResponseToGetDataRequest")]
Message GetData();
}
}
namespace WcfServiceRaw
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
public class Service1 : IService1
{
public Message GetData()
{
// Create body
TestDataWriter body = new TestDataWriter("<test>data</test>");
// Create messatge
MessageVersion ver = OperationContext.Current.IncomingMessageVersion;
Message msg = Message.CreateMessage(ver, "ResponseToGetDataRequest", body);
//Debug.WriteLine(msg.ToString());
return msg;
}
}
class TestDataWriter : BodyWriter
{
string _data;
public TestDataWriter(string data)
: base(false)
{
_data = data;
}
protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
{
writer.WriteRaw(_data);
}
}
客户是:
namespace WcfClientRaw
{
class Program
{
static void Main(string[] args)
{
//IMyContract proxy = ChannelFactory<IMyContract>.CreateChannel(new BasicHttpBinding(), new EndpointAddress(address));
WcfServiceRaw.Service1Client proxy = new WcfServiceRaw.Service1Client();
using (proxy as IDisposable)
{
Message msg = proxy.GetData();
Console.WriteLine(msg.ToString());
Console.WriteLine();
XmlDictionaryReader xdr = msg.GetReaderAtBodyContents();
//string exp = "<test>data</test>";
string act = xdr.ReadOuterXml();
//Debug.Assert(exp == act);
Console.WriteLine(act);
Console.ReadLine();
}
}
}
}