XmlReader 示例
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.
设置、生成和运行示例
若要生成 C# 或 Visual Basic .NET 版本的解决方案,请按照 Building the Windows Communication Foundation Samples中的说明进行操作。
要使用单机配置或跨计算机配置来运行示例,请按照运行 Windows Communication Foundation 示例中的说明进行操作。