WCF服務契約開發實踐
WCF是由微軟公司開發的一款.NET Framework 3.5的重要組成部件,它的影音方式很多,有很多重要的功能值得我們去深入研究。比如今天為大家介紹的WCF服務契約就是其中一個比較重要的應用知識。
一個WCF服務契約是一個用元數據屬性[ServiceContract]修飾的.NET接口或類。每個WCF服務可以有一個或多個契約,每個契約是一個操作集合。
首先我們定義一個.NET接口:IStuServiceContract,定義兩個方法分別實現添加和獲取學生信息的功能
- void AddStudent(Student stu);stuCollection GetStudent();
用WCF服務契約模型的元數據屬性ServiceContract標注接口IStuServiceContract,把接口設計為WCF契約。用OperationContract標注AddStudent,GetStudent
GetStudent()返回一個類型為stuCollection類型的集合。AddStudent()需要傳入Student實體類作為參數。
- 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服務契約和客戶交換SOAP信息。在發送端必須把WCF服務和客戶交互的數據串行化為XML并在接收端把XML反串行化。因此客戶傳遞給AddStudent操作的Student對象也必須在發送到服務器之前串行化為XML。WCF默認使用的是一個XML串行化器DataContractSerializer,用它對WCF服務和客戶交換的數據進行串行化和反串行化。
【編輯推薦】