WCF服務(wù)契約開(kāi)發(fā)實(shí)踐
WCF是由微軟公司開(kāi)發(fā)的一款.NET Framework 3.5的重要組成部件,它的影音方式很多,有很多重要的功能值得我們?nèi)ド钊胙芯俊1热缃裉鞛榇蠹医榻B的WCF服務(wù)契約就是其中一個(gè)比較重要的應(yīng)用知識(shí)。
一個(gè)WCF服務(wù)契約是一個(gè)用元數(shù)據(jù)屬性[ServiceContract]修飾的.NET接口或類(lèi)。每個(gè)WCF服務(wù)可以有一個(gè)或多個(gè)契約,每個(gè)契約是一個(gè)操作集合。
首先我們定義一個(gè).NET接口:IStuServiceContract,定義兩個(gè)方法分別實(shí)現(xiàn)添加和獲取學(xué)生信息的功能
- void AddStudent(Student stu);stuCollection GetStudent();
用WCF服務(wù)契約模型的元數(shù)據(jù)屬性ServiceContract標(biāo)注接口IStuServiceContract,把接口設(shè)計(jì)為WCF契約。用OperationContract標(biāo)注AddStudent,GetStudent
GetStudent()返回一個(gè)類(lèi)型為stuCollection類(lèi)型的集合。AddStudent()需要傳入Student實(shí)體類(lèi)作為參數(shù)。
- namespace WCFStudent
- {
- [ServiceContract]
- public interface IStuServiceContract
- {
- [OperationContract]
- void AddStudent(Student stu);
- [OperationContract]
- stuCollection GetStudent();
- }
- [DataContract]
- public class Student
- {
- private string _stuName;
- private string _stuSex;
- private string _stuSchool;
- [DataMember]
- public string StuName
- {
- get { return _stuName; }
- set { _stuName = value; }
- }
- [DataMember]
- public string StuSex
- {
- get { return _stuSex; }
- set { _stuSex = value; }
- }
- [DataMember]
- public string StuSchool
- {
- get { return _stuSchool; }
- set { _stuSchool = value; }
- }
- }
- public class stuCollection : List<Student>
- {
- }
- }
WCF服務(wù)契約和客戶(hù)交換SOAP信息。在發(fā)送端必須把WCF服務(wù)和客戶(hù)交互的數(shù)據(jù)串行化為XML并在接收端把XML反串行化。因此客戶(hù)傳遞給AddStudent操作的Student對(duì)象也必須在發(fā)送到服務(wù)器之前串行化為XML。WCF默認(rèn)使用的是一個(gè)XML串行化器DataContractSerializer,用它對(duì)WCF服務(wù)和客戶(hù)交換的數(shù)據(jù)進(jìn)行串行化和反串行化。
【編輯推薦】