WCF使用方式比较灵活,在程序员眼中,它占据着非常重要的地位。我们在这篇文章中将会为大家详细讲解一下有关WCF消息模式的相关应用方式,以方便大家在实际应用中能够获得一些帮助。
最简单就是WCF消息模式就是方法参数,所有的基本类型可以直接被序列化。我们还可以使用 MessageParameterAttribute 为参数定义消息名称。
[ServiceContract]
public interface IContract
{
[OperationContract]
double Add(double a, double b);
[OperationContract]
void Test([MessageParameter(Name="myString")]string s);
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
对于WCF消息模式中的自定义类型,我们可以使用 DataContractAttribute 或 MessageContractAttribute 来定义,这些在前面的章节已经提过,此处不再做进一步说明。
WCF 服务方法支持 ref / out 关键字,也就是说底层引擎会重新为添加了关键字的对象赋予返回值。我们使用 "Message Logging" 和 "Service Trace Viewer" 查看一下 Reply Message。
Server.cs
[ServiceContract]
public interface IContract
{
[OperationContract]
double Add(double a, ref double b);
}
public class MyService : IContract
{
public double Add(double a, ref double b)
{
b += 2;
return a + b;
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
client.cs
using (ContractClient client = new ContractClient
(new BasicHttpBinding(),
new EndpointAddress("http://localhost:8080/myservice")))
{
double b = 2;
double c = client.Add(1, ref b);
Console.WriteLine("c={0};b={1}", c, b);
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
Reply Message
< MessageLogTraceRecord>
< s:Envelope xmlns:s="http://...">
< s:Header>
< Action s:mustUnderstand="1" xmlns="http://...">
http://tempuri.org/IContract/AddResponse< /Action>
< /s:Header>
< s:Body>
< AddResponse xmlns="http://tempuri.org/">
< AddResult>5< /AddResult>
< b>4< /b>
< /AddResponse>
< /s:Body>
< /s:Envelope>
< /MessageLogTraceRecord>
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
在 Reply Message 中除了返回值 "AddResult" 外,还有 "b"。:-)
在进行WCF消息模式的处理时,需要注意的是,即便我们使用引用类型的参数,由于 WCF 采取序列化传送,因此它是一种 "值传递",而不是我们习惯的 "引用传递"。看看下面的例子,注意方法参数和数据结果的不同。
Server.cs
[DataContract]
public class Data
{
[DataMember]
public int I;
}
[ServiceContract]
public interface IContract
{
[OperationContract]
void Add(Data d);
[OperationContract]
void Add2(ref Data d);
}
public class MyService : IContract
{
public void Add(Data d)
{
d.I += 10;
}
public void Add2(ref Data d)
{
d.I += 10;
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
Client.cs
using (ContractClient client =
new ContractClient(new BasicHttpBinding(),
new EndpointAddress("http://localhost:8080/myservice")))
{
Data d = new Data();
d.I = 1;
client.Add(d);
Console.WriteLine("d.I={0}", d.I);
Data d2 = new Data();
d2.I = 1;
client.Add2(ref d2);
Console.WriteLine("d2.I={0}", d2.I);
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
输出:
d.I=1
d2.I=11
以上就是对WCF消息模式的相关介绍。
【编辑推荐】