XmlReader 示例演示如何使用 XmlReader 处理消息正文。 此示例基于实现计算器服务的入门。 添加了一个额外的服务操作Sum
,它接受一条消息,该消息包含一组要相加的值。 服务利用 XmlReader 读取消息。
注释
本示例的设置过程和生成说明位于本主题末尾。
计算器接口包括一个名为 Sum
接受 Message 参数的服务作,如以下示例代码所示。
public interface ICalculator
{
[OperationContract]
double Add(double n1, double n2);
[OperationContract]
double Subtract(double n1, double n2);
[OperationContract]
double Multiply(double n1, double n2);
[OperationContract]
double Divide(double n1, double n2);
[OperationContract]
Message Sum(Message message);
}
客户端按如下方式访问 Sum
,首先创建整数值数组,再创建来自该数组的消息,接着使用创建的消息调用 Sum
方法,如下面的示例代码所示。
CalculatorClient client = new CalculatorClient();
//...
// Call the Sum service operation.
int[] values = { 1, 2, 3, 4, 5 };
using (new OperationContextScope(client.InnerChannel))
{
Message request = Message.CreateMessage(OperationContext.Current.OutgoingMessageHeaders.MessageVersion, "http://Microsoft.ServiceModel.Samples/ICalculator/Sum", values);
Message reply = client.Sum(request);
int sum = reply.GetBody<int>();
Console.WriteLine("Sum(1,2,3,4,5) = {0}", sum);
}
在服务中,服务操作Sum
的实现使用XmlReader对象对消息正文中用于求和的值进行循环访问。 调用 GetReaderAtBodyContents 该方法以访问消息正文,如以下示例代码所示。
public int Sum(Message message)
{
int sum = 0;
string text = "";
//The body of the message contains a list of numbers that are read
//directly using an XmlReader.
XmlReader body = message.GetReaderAtBodyContents ();
while (body.Read())
{
text = body.ReadString().Trim();
if (text.Length>0)
{
sum += Convert.ToInt32(text);
}
}
body.Close();
Message response = Message.CreateMessage(
"http://Microsoft.ServiceModel.Samples/ICalculator/SumResponse",
sum);
return response;
}
运行示例时,作的请求和响应将显示在客户端控制台窗口中。 在客户端窗口中按 Enter 关闭客户端。
Add(100,15.99) = 115.99
Subtract(145,76.54) = 68.46
Multiply(9,81.25) = 731.25
Divide(22,7) = 3.14285714285714
Sum(1,2,3,4,5) = 15
Press <ENTER> to terminate client.
设置、生成和运行示例
确保已为 Windows Communication Foundation 示例 执行One-Time 安装过程。
若要生成解决方案的 C# 或 Visual Basic .NET 版本,请按照 生成 Windows Communication Foundation 示例中的说明进行操作。
若要在单台计算机或跨计算机配置中运行示例,请按照 运行 Windows Communication Foundation 示例中的说明进行操作。