WCF消息模式基本內(nèi)容簡述
WCF使用方式比較靈活,在程序員眼中,它占據(jù)著非常重要的地位。我們在這篇文章中將會為大家詳細講解一下有關WCF消息模式的相關應用方式,以方便大家在實際應用中能夠獲得一些幫助。
最簡單就是WCF消息模式就是方法參數(shù),所有的基本類型可以直接被序列化。我們還可以使用 MessageParameterAttribute 為參數(shù)定義消息名稱。
- [ServiceContract]
- public interface IContract
- {
- [OperationContract]
- double Add(double a, double b);
- [OperationContract]
- void Test([MessageParameter(Name="myString")]string s);
- }
對于WCF消息模式中的自定義類型,我們可以使用 DataContractAttribute 或 MessageContractAttribute 來定義,這些在前面的章節(jié)已經(jīng)提過,此處不再做進一步說明。
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;
- }
- }
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);
- }
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>
在 Reply Message 中除了返回值 "AddResult" 外,還有 "b"。:-)
在進行WCF消息模式的處理時,需要注意的是,即便我們使用引用類型的參數(shù),由于 WCF 采取序列化傳送,因此它是一種 "值傳遞",而不是我們習慣的 "引用傳遞"。看看下面的例子,注意方法參數(shù)和數(shù)據(jù)結(jié)果的不同。
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;
- }
- }
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);
- }
輸出:
d.I=1
d2.I=11
以上就是對WCF消息模式的相關介紹。
【編輯推薦】